1. 程式人生 > >十、python中的檔案操作

十、python中的檔案操作

開啟檔案
f = open(“test.py”,”w or r”)
r w a(追加)
rb wb ab(二進位制) 例如圖片 視訊
r+ w+ a+ (可讀可寫)
rb+ wb+ ab+ 操作圖片 音訊
關閉檔案
f.close()
讀檔案 f.read() 讀取全部檔案內容
讀取一定位元組的內容
f.read(數字)
寫檔案內容
f.write()
readline() 一行一行讀取
readlines() 將一行一行讀取的結果用列表存起來

例子:製作檔案的備份
'''應用1:製作檔案的備份
'''
#1、獲取需要複製的檔名: old_file_name = input("please input the file name you need to copy:") #2、開啟需要複製的檔案 old_fid = open(old_file_name,'r') #3、新建一個檔案 #new_file_name = "[copy]"+ old_file_name #new_fid = open("new_file.txt",'w') #test.txt------------>test[copy].txt position = old_file_name.rfind('.') new_file_name = old_file_name[:position] + "[copy]"
+ old_file_name[position:] new_fid = open(new_file_name,'w') #4、從舊檔案中讀取內容到新檔案中 #content = old_fid.read() #直接讀取所有內容到記憶體中會造成記憶體容量不足 while True: content = old_fid.read(1024) #每一次讀取一定量的內容 if len(content) == 0: break new_fid.write(content) #5、關閉兩個檔案 old_fid.close() new_fid.close()
問題:如果一個檔案很大,比如5G,試想應該怎麼樣才能把檔案的資料讀取到記憶體然後進行處理呢?
當讀取大檔案時候,禁止使用read()一次性讀取所有內容,而應該是把內容分次數進行存取,通過使用迴圈來進行實現

定位讀寫

定位讀寫(不從開始,從某個特定位置開始進行讀寫)
seek(偏移量,指標位置) 指標位置值有三種;0(檔案開頭) 1(當前位置) 2(檔案末尾)

f = open("test.txt",'r')
f.seek(2,0) #從檔案開頭處偏移兩個位置處進行操作
print(f.readline())
print(f.read())
print(f.tell())  #獲取指標位置
f.seek(0,0)  #將指標重新指向檔案的開頭處
print(f.tell())
print(f.read())

檔案以及資料夾操作

import os
重新命名檔案:os.rename()
刪除檔案:os.remove()
建立資料夾:os.mkdir()
刪除資料夾:os.rmdir()
返回當前操作的絕對路徑:os.getcwd()
改變操作路徑:os.chdir()
獲取目錄列表:os.listdir(“./”)

批量重新命名例子

import os
#1、獲取要重新命名的資料夾
folder_name = input("please the folder name that you need to rename:")
#2、獲取指定的資料夾裡面的所有檔名字
file_names = os.listdir(folder_name) #返回一個列表
#os.chdir(folder_name)
#3、重新命名
for name in file_names:
    print(name)
    old_file_name = folder_name + '/' + name
    new_file_name = folder_name + '/' + 'JD-' + name
    os.rename(old_file_name,new_file_name)  #注意路徑問題