Python可以用於處理文本文件和二進制文件,比如創建文件、讀寫文件等操作。本文介紹Python處理目錄以及文件的相關方法。
下面先來介紹python目錄處理相關方法。
目錄操作
1. 獲取當前代碼路徑
test_folder.py
import os
import sys
print(__file__)
print(sys.argv[0])
print(os.path.realpath(__file__))
print(os.path.abspath(sys.argv[0]))
Out:
D:/ProgramWorkspace/PythonNotes/03-File-Handling/test_folder.py
D:/ProgramWorkspace/PythonNotes/03-File-Handling/test_folder.py
D:\ProgramWorkspace\PythonNotes\03-File-Handling\test_folder.py
D:\ProgramWorkspace\PythonNotes\03-File-Handling\test_folder.py
2. 獲取當前文件__file__
的所在目錄
print(os.getcwd())
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.split(os.path.realpath(__file__))[0])
path = os.path.dirname(os.path.realpath(__file__))
Out:
D:\ProgramWorkspace\PythonNotes\03-File-Handling
D:\ProgramWorkspace\PythonNotes\03-File-Handling
D:\ProgramWorkspace\PythonNotes\03-File-Handling
3. 獲取當前文件名名稱
print(os.path.basename(sys.argv[0])) # 當前文件名名稱
print(os.path.basename(__file__))
Out:
test_folder.py
test_folder.py
4. 拼接路徑
path = os.path.dirname(os.path.realpath(__file__))
filename = os.path.basename(__file__)
abspath = os.path.join(path, filename)
print(abspath)
Out:
D:\ProgramWorkspace\PythonNotes\03-File-Handling\test_folder.py
5. 創建目錄
判斷目錄是否存在:
os.path.exists(path)
創建目錄
if not os.path.exists(path):
print(f"創建文件夾: {path}")
os.makedirs(path)
文件操作
1. 創建文本文件
text = "Hello World!"
newfilepath = os.path.join(path, "newfile.txt")
file = open(newfilepath, 'w')
file.write(text) # 寫入內容信息
file.close()
2. 判斷文件是否存在
print(os.path.isfile(path))
print(os.path.isfile(newfilepath))
print(os.path.exists(newfilepath))
Out:
False
True
True
os.path.isfile
用於判斷是否為文件且是否存在,os.path.exists
也可以用於判斷文件是否存在,但還是建議使用os.path.isfile
判斷文件,os.path.exists
判斷目錄是否存在。比如,某個文件為newfile,使用這兩個方法都會返回True,無法判斷到底是文件還是目錄。
3. 判斷文件屬性
print(os.access(newfilepath,os.F_OK)) # 文件是否存在
print(os.access(newfilepath,os.R_OK)) # 文件是否可讀
print(os.access(newfilepath,os.W_OK)) # 文件是否可以寫入
print(os.access(newfilepath,os.X_OK)) # 文件是否有執行權限
Out:
True
True
True
True
os.access(newfilepath,os.F_OK)
也可以用於判斷文件是否存在。
4. 打開文件
打開文本文件或者二進制文件可以使用 open()
方法:
f = open(filename, mode)
幾種文件打開模式:
b
:二進制模式t
:文本模式(默認)r
: 打開存在的文件,讀操作(默認)。w
: 打開文件,寫操作,先前文件中的內容會被刪除。如果文件不存在會自動創建。a
: 打開文件,追加操作,不會刪除先前文件中的內容。如果文件不存在會自動創建。x
:創建新文件,寫操作,使用此模式打開存在的文件會拋出異常。r+
: 讀、寫操作,不會刪除先前文件中的內容,但是會覆蓋內容。w+
: 寫、讀操作,會刪除先前文件中的內容。a+
: 追加、讀操作,不會刪除和覆蓋先前文件中的內容。x+
:創建新文件,讀寫操作。
open()
方法的默認模式為 rt
模式,也就是讀文本文件。
另外需要注意filename的寫法,比如文件路徑是:D:\test.txt
,其中\t
可能會被轉義,需要自前面加一個 r
:
f = open(r"D:\test.txt", "w")
5. 寫文件
讀寫文件都需要先打開文件,返回一個文件對象,然后對文件對象進行讀寫操作。寫文件需要設置寫權限,比如 w
、w+
、a
模式。
寫文件主要包括兩種方法:
file.write(str)
:寫入字符串file.writelines(list)
:寫入字符串列表,用於同時插入多個字符串。
舉個栗子:
file = open("newfile.txt", 'w')
text1 = "Hello World!\n你好,世界!\r"
file.write(text1) # 寫入內容信息
text2 = ["To the time to life, \n", "rather than to life in time.\r"]
file.writelines(text2)
file.close()
w
模式會刪除先前文件中的內容,如果不想刪除,需要直接追加到后面,可以使用a
和 a+
模式:
file = open("newfile.txt", 'a')
6. 讀文件
常見的讀取文件方法有以下幾種:
- in操作符
- read():讀取所有數據,返回一個字符串。
- readline():讀取第一行
- readlines():讀取所有行,每行保存為列表的一個元素。
# 打開並讀取文件
file = open("newfile.txt", 'r')
for line in file:
print(line)
print()
file.seek(0, 0)
print(file.read(5)) #
print()
file.seek(0, 0)
print(file.readline(12))
print()
file.seek(0, 0)
print(file.readlines())
print()
file.close()
執行結果:
Hello World!
你好,世界!
To the time to life,
rather than to life in time.
Hello
Hello World!
['Hello World!\n', '你好,世界!\n', 'To the time to life, \n', 'rather than to life in time.\n']
讀取file對象的所有內容后,文本的光標會移動到最后,再次讀取file需要將光標移到前面,使用 file.seek(0, 0)
方法可以將光標移到前面。還有一種解決方案是將讀取的內容存一個在局部變量中。
7. with語句
with語句可用於異常處理,可以確保資源的適當獲取及自動釋放。使用with語句后就不需要調用file.close()
語句了,它會自動釋放。
text1 = "Hello World!\n你好,世界!\r"
text2 = ["To the time to life, \n", "rather than to life in time.\r"]
# 寫
with open("newfile.txt", "w") as file:
file.write(text1)
file.writelines(text2)
# 讀
with open("newfile.txt", "r+") as file:
print(file.read())
with語句對處理大文件非常有用,比如10G大小的文件, with語句會進行上下文管理。