在Ubuntu中,Python可以通過內置的open()
函數進行文件操作。open()
函數用于打開一個文件,并返回一個文件對象,然后可以使用該文件對象進行讀寫操作。以下是一些基本的文件操作示例:
# 打開一個文件用于讀取
file = open('example.txt', 'r')
# 打開一個文件用于寫入(如果文件不存在,會自動創建)
file = open('example.txt', 'w')
# 打開一個文件用于追加(如果文件不存在,會自動創建)
file = open('example.txt', 'a')
# 讀取整個文件內容
content = file.read()
print(content)
# 逐行讀取文件內容
for line in file:
print(line, end='')
# 讀取指定數量的字符
content = file.read(10)
print(content)
# 關閉文件
file.close()
# 寫入字符串到文件
file.write('Hello, World!\n')
# 寫入多行內容
file.writelines(['Line 1\n', 'Line 2\n'])
# 關閉文件
file.close()
# 追加字符串到文件
file.write('Appended text\n')
# 關閉文件
file.close()
with
語句進行文件操作使用with
語句可以自動管理文件的打開和關閉,即使在發生異常時也能確保文件被正確關閉。
# 讀取文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 寫入文件
with open('example.txt', 'w') as file:
file.write('New content')
# 追加內容到文件
with open('example.txt', 'a') as file:
file.write('Appended text')
在Ubuntu中,文件路徑通常使用正斜杠(/
)作為分隔符??梢允褂肞ython的os
模塊來處理文件路徑。
import os
# 獲取當前工作目錄
current_directory = os.getcwd()
print(current_directory)
# 拼接文件路徑
file_path = os.path.join(current_directory, 'example.txt')
print(file_path)
# 檢查文件是否存在
if os.path.exists(file_path):
print('File exists')
else:
print('File does not exist')
# 創建目錄
os.makedirs('new_directory', exist_ok=True)
# 刪除文件
os.remove(file_path)
# 刪除目錄
os.rmdir('new_directory')
通過這些基本的文件操作,你可以在Ubuntu中使用Python進行各種文件處理任務。