讀取整個檔案
with open
('text_files/file_path'
) as file_object:
contents = file_object.
read()
print
(contents)
逐行讀取
with open
(filename) as file_object:
for line in file_object:
print
(line.
rstrip()
) #消除末尾換行符(空白)
建立乙個包含檔案隔行內容的列表
filename =
'file_name.txt'
with open
(filename) as file_object:
lines = file_object.
readlines()
for line in lines:
print
(line.
rstrip()
)
使用檔案的內容
filename =
'pi_digits.txt'
with open
(filename) as file_object:
lines = file_object.
readlines()
pi_string =
''for line in lines:
pi_string +
= line.
rstrip()
print
(pi_string)
print
(len
(pi_string)
)
寫入空檔案
''
' write_message.py'
''filename =
'programming.txt'
with open
(filename,
'w') as file_object:
file_object.
write
("i love programming."
)
''
'programming.txt'
''i love programming.
寫入多行
filename =
'programming.txt'
with open
(filename,
'w') as file_object:
file_object.
write
("i love programming.\n"
) file_object.
write
("i love creating new games."
)
''
'programming.txt'
''i love programming.
i love creating new games.
附加到檔案
filename =
'programming.txt'
with open
(filename,
'w') as file_object:
file_object.
write
("i love programming.\n"
) file_object.
write
("i love creating new games."
) file_object.
write
("i also love finding meaning in large datasets.\n"
) file_object.
write
()
''
'programming.txt'
''i love programming.
i love creating new games.
i also love finding meaning in large datasets.
我們開啟檔案時指定了實參』a』 ,以便將內容附加到檔案末尾,而不是覆蓋檔案原來的內容。我們寫入了兩行,它們被新增到檔案programming.txt末尾。最終的結果是,檔案原來的內容還在,它們後面是我們剛新增的內容。 python 基礎 檔案
引入模組 import zipfile zip檔案格式是通用的文件壓縮標準,在ziplib模組中,使用zipfile類來操作zip檔案,下面具體介紹一下 zipfile.zipfile file mode compression allowzip64 功能 建立乙個zipfile物件,表示乙個zip...
python基礎 檔案讀寫
1.讀寫方式 f open text r encoding utf 8 2.寫讀方式 f open text w encoding utf 8 3.追加方式 f open text a encoding utf 8 4.讀方式 f open text r encoding utf 8 5.寫方式 f...
Python基礎 檔案操作
使用 open 能夠開啟乙個檔案,open 的第乙個引數為檔名和路徑 my file.txt 第二個引數為將要以什麼方式開啟它,比如w為可寫方式.如果計算機沒有找到 my file.txt 這個檔案,w 方式能夠建立乙個新的檔案,並命名為 my file.txt 例項 text tthis is m...