一、實驗物件:《零基礎學Python》6道實體和2道實戰
二、實驗環境:IDLE Shell 3.9.7
三、實驗目的:學習如何在Python中進行檔案和目錄的相關操作
四、實驗程序:
- 實體01 創建并打開記錄螞蟻莊園動態的檔案

點擊查看代碼
print("\n","="*10,"螞蟻莊園動態","="*10)
file=open('message.txt','w')
print("\n 即將顯示......\n")
運行結果:

- 實體02 向螞蟻莊園的動態檔案寫入一條資訊

點擊查看代碼
print("\n","="*10,"螞蟻莊園動態","="*10)
file=open('message.txt','w')
file.write("你使用了1張加速卡,小雞擼起袖子開始雙手吃飼料,進食速度大大加快,\n")
print("\n 寫入了一條動態......\n")
file.close()
運行結果:


- 實體03 顯示螞蟻莊園的動態

點擊查看代碼
print("\n","="*25,"螞蟻莊園動態","="*25,"\n")
with open('message.txt','r')as file:
message=file.read()
print(message)
print("\n","="*29,"over","="*29,"\n")
運行結果:

- 實體04 逐行顯示螞蟻莊園的動態

點擊查看代碼
print("\n","="*35,"螞蟻莊園動態","="*35,"\n")
with open('message.txt','r')as file:
number=0
while True:
number+=1
line=file.readline( )
if line=='':
break
print(number,line,end="\n")
print("\n","="*39,"over","="*39,"\n")
運行結果:

- 實體05 遍歷指定目錄

點擊查看代碼
import os
path="C:\\demo"
print("【",path,"】目錄下包括的檔案和目錄:")
for root,dirs,files in os.walk(path, topdown=True):
for name in dirs:
print("●",os.path.join(root,name))
for name in files:
print("◎",os.path.join(root,name))
運行結果:

- 實體06 獲取檔案基本資訊

點擊查看代碼
import os
fileinfo=os.stat("Ten_sl_01.py")
print("檔案完整路徑:",os.path.abspath("Ten_sl_01.py"))
print("索引號:",fileinfo.st_ino)
print("設備名:",fileinfo.st_dev)
print("檔案大小:",fileinfo.st_size,"位元組")
print("最后一次訪問時間:",fileinfo.st_atime)
print("最后一次修改時間:",fileinfo.st_mtime)
print("最后一次狀態變化時間:",fileinfo.st_ctime)
運行結果:

- 實戰01 根據當前時間創建檔案

點擊查看代碼
import os
import time
def ltime_file(n):
for i in range(1, n + 1):
localTime = time.strftime("%Y%m%d%H%M%S", time.localtime())
file_name=localTime
f = open(file_name+".txt",'a')
print("file" + " " + str(i) + ":" + str(localTime) + ".txt")
time.sleep(1) # 休眠一秒
print('生成檔案成功!')
if __name__ == '__main__':
n = int(input("請輸入需要生成的檔案數:"))
ltime_file(n)
運行結果:


- 實戰02 批量添加檔案夾

點擊查看代碼
import os
n=input("請輸入需要生成的檔案夾個數:")
w=int(n)
for i in range(1, w+1):
file_name =str(i)
dir_name = file_name
os.mkdir(dir_name)
print("檔案夾"+str(i)+"創建成功!")
運行結果:


轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/531821.html
標籤:其他
上一篇:noi 1.4 11晶晶赴約會
