读取文件
1、读取文件
(1)读取整个文件
read():读取整个文件
with open('xxx.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
open():打开文件
关键字with 在不再需要访问文件后将其关闭。
相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。因为read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。
文件路径
相对文件路径
with open('子文件夹\xxx.txt') as file_object:
绝对文件路径
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
注意:在Windows系统中路径使用反斜杠 \
(用VSC测试发现必须输入绝对文件路径,不然电脑找不到地方)
(2)逐行读取文件
filename = 'xxx.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
(3)将文件各行储存到列表
readlines()
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
此时可在在with 代码块外访问文件的内容。
2、写入文件
(1)写入空文件
write()
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
第二个实参('w' ):以写入模式 打开这个文件。
打开文件时,可指定读取模式 ('r' )、写入模式 ('w' )、附加模式 ('a' )、读取和写入文件模式('r+' )。如果省略了模式实参,Python将以默认的只读模式(r)打开文件。
如果要写入的文件不存在,函数open() 将自动创建它。然而,以写入('w' )模式打开文件时,如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
(2)写入多行
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.\n")
函数write() 不会在写入的文本末尾添加换行符
(3)附加到文件
附加模式 ('a' )
with open(filename, 'a') as file_object: