with open('test.txt') as file_object: # 使用with關鍵字後,不需要手動關閉檔案
contents = file_object.read()
print(contents)
hello,world!
i'm a robot.
who are you?
with open('text_files/filename.txt') as file_object:
with open('test.txt') as file_object:
for line in file_object:
print("-"+line)
-hello,world!
-i'm a robot.
-who are you?
# 使用關鍵字with時,open()返回的檔案物件只在with**塊內可用。
# 如果要在with**塊外訪問檔案的內容,可在with**塊將檔案的各行儲存在乙個列表中,
# 並在with**塊外使用該列表
with open('test.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print("-"+line)
-hello,world!
-i'm a robot.
-who are you?
with open('write_test.txt','w') as file_object:
file_object.write('i love python.')
with open('write_test.txt','w') as file_object:
file_object.write('i love python.\n')
file_object.write('i love coding.\n')
with open('write_test.txt','a') as file_object:
file_object.write("but i am a ai.\n")
python 檔案操作
簡明 python 教程 中的例子,python 執行出錯,用open代替file 可以執行。poem programming is fun when the work is done if you wanna make your work also fun use python f open e ...
python檔案操作
1,將乙個路徑名分解為目錄名和檔名兩部分 a,b os.path.split c 123 456 test.txt print a print b 顯示 c 123 456 test.txt 2,分解檔名的副檔名 a,b os.path.splitext c 123 456 test.txt pri...
Python 檔案操作
1.開啟檔案 如下 f open d test.txt w 說明 第乙個引數是檔名稱,包括路徑 第二個引數是開啟的模式mode r 唯讀 預設。如果檔案不存在,則丟擲錯誤 w 只寫 如果檔案 不存在,則自動建立檔案 a 附加到檔案末尾 r 讀寫 如果需要以二進位制方式開啟檔案,需要在mode後面加上...