今天我們要一起探索的是Python編程中的一個(gè)非常實(shí)用且基礎(chǔ)的領(lǐng)域——文件與目錄管理。無論是處理個(gè)人數(shù)據(jù)、自動(dòng)化辦公任務(wù)還是構(gòu)建復(fù)雜的軟件系統(tǒng),這些技巧都將大大提升你的工作效率。準(zhǔn)備好了嗎?讓我們一起動(dòng)手吧!

目標(biāo):學(xué)習(xí)如何安全地打開文件并讀取內(nèi)容。
技巧:使用with open()語句自動(dòng)管理文件資源,防止忘記關(guān)閉文件。
示例代碼:
with open('example.txt', 'r') as file: content = file.read()print(content)這段代碼會(huì)打開名為'example.txt'的文件,讀取其全部內(nèi)容并打印出來,之后自動(dòng)關(guān)閉文件。
技巧:使用for line in file:逐行讀取文件,適合處理大文件。
示例:
with open('example.txt', 'r') as file: for line in file: print(line.strip()) # strip()移除行尾換行符目標(biāo):學(xué)會(huì)向文件追加或覆蓋內(nèi)容。
使用'w'模式覆蓋原有內(nèi)容,'a'模式追加內(nèi)容。
示例(追加):
with open('example.txt', 'a') as file: file.write("/nHello, Python!")技巧:使用open函數(shù)以寫入模式('w')打開不存在的文件即可創(chuàng)建它。
注意,這會(huì)覆蓋同名文件。
使用os模塊來操作目錄。
示例:列出當(dāng)前目錄下的所有文件和子目錄。
import osprint(os.listdir())使用os.path.exists(path)檢查路徑是否存在。
示例:
if os.path.exists('new_directory'): print("Directory exists!")else: os.mkdir('new_directory') # 創(chuàng)建目錄使用os.rename(oldname, newname)重命名文件。
注意:跨目錄移動(dòng)文件時(shí),也可以用此方法。
使用os.remove(filename)小心刪除文件。
刪除前最好檢查文件是否存在,避免錯(cuò)誤。
使用os.walk(top)來遞歸地遍歷目錄樹。
示例:
for root, dirs, files in os.walk('.'): # '.'表示當(dāng)前目錄 for name in files: print(os.path.join(root, name))pathlib模塊提供了一種更面向?qū)ο蟮姆绞絹硖幚砺窂健?span style="display:none">gQN28資訊網(wǎng)——每日最新資訊28at.com
示例:
from pathlib import Pathmy_file = Path('my_folder/my_file.txt')my_file.touch() # 創(chuàng)建文件print(my_file.name) # 輸出文件名對(duì)于圖片、音頻等二進(jìn)制文件,使用'rb'或'wb'模式。
示例(讀取圖片):
with open('image.jpg', 'rb') as file: image_data = file.read()12. 錯(cuò)誤處理
在文件操作中,使用try...except處理可能的異常,如文件不存在錯(cuò)誤(FileNotFoundError)。
示例:
try: with open('nonexistent.txt', 'r') as file: print(file.read())except FileNotFoundError: print("文件未找到,請(qǐng)檢查路徑。")通過這些步驟,你已經(jīng)掌握了Python文件與目錄管理的基礎(chǔ)和一些進(jìn)階技巧。
技巧:利用循環(huán)和字符串操作,批量重命名文件,這對(duì)于整理大量文件特別有用。
示例代碼(將一個(gè)目錄下所有.jpg文件重命名為序列格式):
import osdirectory = 'image_folder'counter = 1for filename in os.listdir(directory): if filename.endswith(".jpg"): # 確定是.jpg文件 new_filename = f"image_{counter}.jpg" src = os.path.join(directory, filename) dst = os.path.join(directory, new_filename) os.rename(src, dst) counter += 1shutil模塊提供了高級(jí)文件和文件集合操作,如復(fù)制、移動(dòng)文件和目錄。
文件復(fù)制:
import shutilshutil.copy('source.txt', 'destination.txt')目錄復(fù)制(包括目錄下所有內(nèi)容):
shutil.copytree('source_folder', 'destination_folder')使用zipfile模塊處理.zip文件,tarfile處理.tar文件。
壓縮文件:
import zipfilewith zipfile.ZipFile('archive.zip', 'w') as zipf: zipf.write('file_to_compress.txt')解壓文件:
with zipfile.ZipFile('archive.zip', 'r') as zip_ref: zip_ref.extractall('unzip_folder')對(duì)于非常大的文件,可以考慮分塊讀寫,避免一次性加載到內(nèi)存中。
分塊讀取:
chunk_size = 1024 * 1024 # 1MBwith open('large_file.txt', 'r') as f: while True: chunk = f.read(chunk_size) if not chunk: break process(chunk) # 假設(shè)process是處理數(shù)據(jù)的函數(shù)利用Path對(duì)象的靈活性,可以更自然地操作路徑。
創(chuàng)建路徑鏈接:
from pathlib import Pathlink = Path('shortcut').symlink_to('target_folder')檢查文件類型:
if my_file.is_file(): print("是文件")elif my_file.is_dir(): print("是目錄")通過這些高級(jí)技巧,你的Python文件與目錄管理能力將進(jìn)一步提升。
本文鏈接:http://m.www897cc.com/showinfo-26-92134-0.html實(shí)用 Python:文件與目錄管理的 17 個(gè)技巧
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com