Python程序-写文件
时间:2020-01-09 10:44:20 来源:igfitidea点击:
在本教程中,我们将看到使用Python写入文件的不同选项。
- 使用write()方法,我们可以将传递的字符串写入文件。
- 使用writelines(lines)方法可以编写行列表。
- 以二进制模式写入文件。
1.使用write()方法在Python中写入文件
f.write(string)将string的内容写入文件并返回写入的字符数。要在Python中写入文件,应在写入模式下打开文件。请注意,以写模式(w)打开将创建文件(如果不存在)或者覆盖文件(如果已存在)。
def write_file(fname):
try:
f = open(fname, 'w')
f.write("This is Line 1.\n")
f.write("This is Line 2.")
finally:
f.close()
write_file("F:/theitroad/Python/test.txt")
在这里,write_file()方法将文件路径作为参数,并以写模式打开该文件。将两行写入文件,然后关闭文件。
另一种打开文件的方法是使用with关键字,它会自动关闭文件。首选与open一起使用,因为它会使代码更短。
def write_file(fname):
with open (fname, 'w') as f:
chars_written = f.write("This is Line 1.\n")
print('Characters written to the file', chars_written);
f.write("This is Line 2.")
如我们所见,现在不需要try-finally块,因为打开文件操作完成后,打开会自动关闭文件。
如果要写入任何其他类型的对象,则必须先将其转换为字符串(在文本模式下)或者字节对象(在二进制模式下),然后再将其写入文件。例如,在下面的程序中,我们要向该文件中写入元组,因为它必须先转换为str。
def write_file(fname):
with open(fname, 'w') as f:
value = ('One', 1)
s = str(value) # convert the tuple to string
f.write(s)
2.使用writelines(lines)方法可以编写行列表。
如果有行列表,则可以使用writelines()方法编写它。
def write_file(fname):
with open(fname, 'w') as f:
lines = ["This is the first line\n", "This is the second line\n", "This is the third line"]
f.writelines(lines)
3.使用" w +"模式写入和读取文件。
以下程序以" w +"模式打开一个文件,用于写入和读取。程序还使用tell()方法获取文件指针的当前位置,并使用seek()方法移至文件的开头。
def write_read_file(fname):
with open(fname, 'w+') as f:
f.write("This is the first line.\n")
f.write("This is the second line.\n")
f.flush()
print("Current position of file pointer- ", f.tell())
f.seek(0, 0)
s = f.read()
print('Content- ', s)
4.用Python编写二进制文件
如果要写入二进制文件,则需要以" wb"模式打开文件。在以下用于复制图像的Python程序中,以二进制模式打开图像文件,然后将其写入另一个文件。
def copy_file():
try:
# Opened in read binary mode
f1 = open('F:/theitroad/Java/Java Collections/collection hierarchy.png', 'rb')
# Opened in write binary mode
f2 = open('F:/theitroad/Python/newimage.png', 'wb')
b = f1.read()
f2.write(b)
print('Coying image completed...')
finally:
f1.close()
f2.close()

