Python 文件操作
1.读取文件
1.1 一次性读取整个文件
with open('test.txt') as file_object:
contents = file_object.read()
print(contents)
open()函数打开test.txt文件,返回一个表示文件的对象,存储在后面指定的file_object中;
read()方法读取file_object所对应的文件的所有内容,默认在文件内容的每一个行末尾加\n
1.2 逐行读取
with open('test.txt') as file_object:
for line in file_object:
print(line.strip())
加上strip()是因为逐行读取默认会在每一个行后面加\n
1.3 将文件内容逐行放入列表
with open('test.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.strip())
readlines()读取file_object对应文件的每一个行内容,默认会在每一个末尾加\n
2.写入文件
2.1 写入空文件
file_name = 'write_in.txt'
with open(file_name,'w') as file_object:
file_object.write('I love Python!')
file_name定义了将要写入的文件名;
open(file_name,‘w’)中的w表示以写入模式打开文件,还有’r’只读模式,'a’追加写模式;如果像前文那样忽略该参数,默认是采用只读模式;
写入模式会将写入文件先清空,然后再写入,请注意安全。
2.2 写入多行
file_name = 'write_in.txt'
with open(file_name,'w') as file_object:
file_object.write('I love Python!')
file_object.write('I love programming!')
写入多行默认是把多个write函数的写入内容都写入到文件的同一个行中,如果要存放在文件中的不同行,以上代码应该改写成:
with open(file_name,'w') as file_object:
file_object.write('I love Python!\n')
file_object.write('I love programming!')
2.3 追加内容到文件
上述已经说明,w写入模式是会先清空文件,再写入内容,但我们很多时候是不需要清空内容的,那么可以使用a追加写模式。
file_name = 'write_in.txt'
with open(file_name,'a') as file_object:
file_object.write('I love Python!')
file_object.write('I love programming!')