写入文件时,写入文本文件使用open('data', 'w'),写入二进制文件则需使用open('data', 'wb')。追加写入文件时,可以使用open('data', 'w+')。写入数据的代码如下:file_object = open('thefile.txt', 'w')file_object.write(all_the_text)file_object.close()写入多行时,使用writelines(...
如何用python读取和写入TIFF文件1
Python处理文件时,需要使用open函数打开文件。打开文件后,务必记得调用close()方法关闭文件。例如,可以使用try/finally结构确保文件最终被关闭。文件打开代码如下:
file_object = open('thefile.txt')
try:
all_the_text = file_object.read()
finally:
file_object.close()
需要注意的是,不能将open语句放在try块内,因为如果打开文件时发生异常,file_object对象将无法执行close()方法。
读取文件时,读取文本文件可以使用open('data', 'r')或open('data'),读取二进制文件则需使用open('data', 'rb')。读取所有内容的代码如下:
file_object = open('thefile.txt')
try:
all_the_text = file_object.read()
finally:
file_object.close()
如果需要读取固定字节,则可以使用while循环结合read(100)方法,直到读取完毕。例如:
file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close()
读取文件每行时,可以使用readlines()方法或直接遍历文件对象。例如:
list_of_all_the_lines = file_object.readlines()
或
for line in file_object:
process line
写入文件时,写入文本文件使用open('data', 'w'),写入二进制文件则需使用open('data', 'wb')。追加写入文件时,可以使用open('data', 'w+')。写入数据的代码如下:
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close()
写入多行时,使用writelines(list_of_text_strings)方法,其性能通常优于使用write一次性写入。2024-11-30