在Python中,可以使用內置的open()函數來打開和操作文件。以下是一些基本的文件讀寫操作示例:
# 使用 'r' 模式打開文件,只讀模式
file = open("example.txt", "r")
# 讀取文件內容
content = file.read()
# 關閉文件
file.close()
print(content)
# 使用 'w' 模式打開文件,寫入模式,如果文件不存在則創建
file = open("example.txt", "w")
# 寫入內容
file.write("Hello, World!")
# 關閉文件
file.close()
# 使用 'a' 模式打開文件,追加模式,如果文件不存在則創建
file = open("example.txt", "a")
# 追加內容
file.write("\nThis is an appended line.")
# 關閉文件
file.close()
首先,打開命令行交互式環境(如Windows的命令提示符或macOS/Linux的終端),然后輸入以下命令來創建一個名為example.txt的文件并寫入一些內容:
echo "Hello, World!" > example.txt
接下來,使用Python讀取并打印文件內容:
python
>>> with open("example.txt", "r") as file:
... content = file.read()
... print(content)
...
Hello, World!
>>>
在這個例子中,我們使用了with語句來自動關閉文件。這是一種更安全的文件操作方式,可以確保文件在使用后正確關閉,即使在讀取文件時發生異常也是如此。