讀檔案
在相應的資料夾下建立乙個list.txt檔案。
#建立乙個包含檔案各行內容的列表
"""將要讀取的檔案的名稱儲存在變數filename中"""
filename = 'list.txt'
with open(filename) as file_obj:
'''呼叫open(),將乙個表示檔案及其內容的物件儲存到了變數file_object中'''
lines = file_obj.readlines()
'''使用readlines()方法讀取每一行,並儲存在列表中'''
for line in lines:
print(line.rstrip())
'''使用rstrip()清除多餘的空格'''
#使用檔案中的內容
filename = 'list.txt'
with open(filename) as file_obj:
lines = file_obj.readlines()
list_one = ''
'''定義乙個變數/列表,用於儲存list.txt檔案中的內容'''
for line in lines:
list_one += line.rstrip()
print(list_one)
print(len(list_one))
2.寫檔案
"""
開啟檔案時,可指定讀取模式('r')、寫入模式('w')、附加模式('a')
或讓你能夠讀取和寫入檔案的模式('r+')
如果你省略了模式實參,將預設以唯讀方式開啟
如果你寫入的檔案不存在,將自動建立。如果檔案已存在,python將在返回
檔案物件前清空該檔案
"""#寫入空檔案
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("i love python !")
#寫入多行
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("i love python !\n")
'''此處使用換行符,避免內容擠在一起'''
file_object.write("hello,everyone!\n")
#附加到檔案
filename = 'programming.txt'
with open(filename,'a') as file_object:
'''此處使用實參 a 以便將內容新增到檔案末尾,而不是覆蓋原檔案內容'''
file_object.write("i love python !")
python 檔案操作,讀檔案,寫檔案
讀取檔案的全部內容 def get f none try f open 致橡樹.txt r encoding utf 8 print f.read except filenotfounderror print 無法開啟指定的檔案 except lookuperror print 指定了未知的編碼 e...
Python讀(read)寫(write)檔案
寫檔案 write w 第乙個位置填寫路徑 path 盡量填寫絕對路徑,好找,如果只寫檔名及字尾,則檔案要在該模組的資料夾內,第二個寫的讀或者寫,r 或者 w r代表讀,w代表寫 n表示換行 f.write s 寫入檔案內 f.close 關閉流 讀檔案 read r 第乙個位置填寫路徑 path ...
python之 檔案讀與寫
模式 描述 r 以讀方式開啟檔案,可讀取檔案資訊。w 以寫方式開啟檔案,可向檔案寫入資訊。如檔案存在,則清空該檔案,再寫入新內容 a 以追加模式開啟檔案 即一開啟檔案,檔案指標自動移到檔案末尾 如果檔案不存在則建立 r 以讀寫方式開啟檔案,可對檔案進行讀和寫操作。r 時,如果不先f.read 則新寫...