Python读写文件是指Python程序可以读取文件中的内容,也可以将内容写入文件中。
读取文件
Python提供了open()
函数来打开文件,并返回一个文件对象,该文件对象提供了一系列方法来读取文件中的内容。
例如,使用read()
方法可以读取文件中的全部内容:
f = open('test.txt', 'r')
content = f.read()
f.close()
也可以使用readline()
方法来读取文件中的一行内容:
f = open('test.txt', 'r')
line = f.readline()
f.close()
写入文件
使用open()
函数打开文件时,可以指定文件的模式,如果指定为'w'
,则可以向文件中写入内容。
例如,使用write()
方法可以将字符串写入文件中:
f = open('test.txt', 'w')
f.write('Hello World!')
f.close()
也可以使用writelines()
方法将一个字符串列表写入文件中:
f = open('test.txt', 'w')
lines = ['Hello', 'World']
f.writelines(lines)
f.close()