檔案
1.讀取整個檔案
filepath="D:\\test.txt"
file_object=open(filepath)
file_content=file_object.read()
print(file_content)
file_object.close()
>>>
111111111111
222222222222
333333333333
444444444444
555555555555
666666666666
777777777777
888888888888
Process finished with exit code 0
更好的一種寫法:
使用with時,open傳回的對象隻在with代碼塊中有用;
filepath="D:\\test.txt"
with open(filepath) as file_object:
file_content=file_object.read()
print(file_content)
>>>
111111111111
222222222222
333333333333
444444444444
555555555555
666666666666
777777777777
888888888888
2.逐行讀取
filepath="D:\\test.txt"
with open(filepath) as file_object:
for line in file_object:
print(line)
使用with時,open傳回的對象隻在with代碼塊中有用;可以将資料存儲在清單中,在外邊列印;
filepath="D:\\test.txt"
with open(filepath) as file_object:
lines=file_object.readline()
print(lines)
3.使用檔案内容
with open(filepath) as file_object:
lines=file_object.readlines()
str=''
for line in lines:
str+=line
print(str)
open函數
1.open函數有兩個參數,第一個參數:告訴檔案所在位置;第二個參數:告訴python是以寫入模式打開該檔案還是隻讀模式打開等
open(filepath,'w'):寫入模式打開filepath檔案
open(filepath,'r'):讀取模式打開filepath檔案
2.如果打開的檔案不存在,則建立
3.以寫入模式打開檔案,因為如果指定的檔案已經存在,python将在傳回檔案對象前清空該檔案
附加模式
1.如果要給檔案添加内容,而不是覆寫原有内容,可以使用附加模型打開檔案;以附加模式打開,python不會在傳回檔案對象前清空檔案,而寫入的檔案都會添加到檔案的末尾
open(filepath,'a'):附加模式打開filepath檔案