十、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)  #注意路徑問題
發佈了65 篇原創文章 · 獲贊 17 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章