超詳細Python文件操作命令知識
前言
在 Python 中,打開文件時需要指定打開文件的模式。常見的文件打開模式包括:
‘r’:讀取模式。默認模式,用于讀取文件內(nèi)容。如果文件不存在,則會引發(fā)
FileNotFoundError錯誤。‘w’:寫入模式。如果文件不存在,則創(chuàng)建文件;如果文件已存在,則先清空文件內(nèi)容,然后寫入新內(nèi)容。
‘a’:追加模式。用于在文件末尾添加新內(nèi)容,而不會影響原有內(nèi)容。如果文件不存在,則創(chuàng)建文件。
打開文件并讀取內(nèi)容
with open("./data/example.txt", "r",encoding="utf-8") as file:
content = file.read()
print(content)
寫入內(nèi)容到文件
with open("./data/example.txt", "w") as file:
file.write("Hello, World!")
逐行讀取文件內(nèi)容
with open("./data/example.txt", "r") as file:
for line in file:
print(line)
追加內(nèi)容到文件
with open("./data/example.txt", "a") as file:
file.write("\nAppending new line!")
文件重命名
import os
os.rename("./data/example.txt", "./data/new_example.txt")
文件刪除
import os
os.remove("./data/example.txt")
檢查文件是否存在
import os
if os.path.exists("./data/example.txt"):
print("文件存在")
else:
print("文件不存在")
創(chuàng)建文件目錄
import os
os.mkdir("example_directory")
刪除文件目錄
import os
os.rmdir("example_directory")復(fù)制文件
兩種方式:
第一種方法適合復(fù)制比較小的文件
第二種方式適合復(fù)制比較大的文件


總結(jié)
到此這篇關(guān)于Python文件操作命令的文章就介紹到這了,更多相關(guān)Python文件操作命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
msvcrt庫在pycharm中運行監(jiān)控鍵盤操作無效問題及解決
文章主要講述在PyCharm中使用msvcrt庫監(jiān)控鍵盤操作時遇到的問題及解決方案,通過勾選“Emulateterminalinoutputconsole”設(shè)置項,解決了按下D鍵和回車無反應(yīng)的問題2026-05-05

