读取文件数据
定义
test.txt
Hello word!
file_test.py
with open("test.txt") as file_object:
datas = file_object.read()
print(datas)
---ans---
Hello word!
open()
函数接受一个参数,为打开文件的名称。
该参数使用绝对路径或者相对路径均可。
关键字with
帮助我们在不需要访问文件后将其关闭。使用with
后,调用open()
函数,不需要再调用close()
函数。
注意:read()
到达文件末尾时返回一个空字符串,调用print()
函数后,会显示出来一个空行。
如果要删除多出来的空行,在print()
语句中使用rstrip()
。
with open("test.txt") as file_object:
datas = file_object.read()
print(datas.rstrip())
逐行读取
with open("test.txt") as file_object:
for line in file_object:
print(line)
---ans---
Hello word!
Hello word!
跟上面提到的一样,每一行的输出结果后多一行空行,消除空行使用rstrip()
with open("test.txt") as file_object:
for line in file_object:
print(line.rstrip())
---ans---
Hello word!
Hello word!
读取存储到列表中
使用readlines()
方法,将每一行存储到一个列表中。
with open("test.txt") as file_object:
lines = file_object.readlines()
print(lines)
---ans---
['Hello word!\n', 'Hello word!']
写入文件数据
定义
要将文本写入文件,在调用open()
时,需要提供一个额外的参数:
- 读取模式(‘r’)
- 写入模式(‘w’)
- 附加模式(‘a’)
- 能够读取和写入文件的模式(‘r+’)
不指定参数,默认为只读模式。
如果写入的文件不存在,函数open()
会自动创建该文件,进行写入。
file_test2.py
with open("test2.txt", "w") as file_object:
file_object.write("Hello Word!!!")
test2.txt
Hello Word!!!
方法write()
,将一个字符串写入指定的文件中。
写入多行
with open("test2.txt", "w") as file_object:
file_object.write("Hello Word!!!\n")
file_object.write("Hello Word!!!")
---ans---
Hello Word!!!
Hello Word!!!
方法write()
不会在写入的文本末尾添加换行符,如果需要写入多行,需要在语句中添加换行符。
继续添加文件内容
file_test3.py
with open("test2.txt", "a") as file_object:
file_object.write("I Love You!!!")
test2.txt
Hello Word!!!
Hello Word!!!I Love You!!!
以附加模式打开文件,写入文件的行,会添加到文件末尾。如果制定的文件不存在,Python会自动创建一个空文件,将数据添加到文件中。