如何读取文件
open()函数 +read()方法
open函数参数 filename mode mode参数可以不写,默认mode参数是“r”
file_object = open('file', 'mode')
例子:
f = open("test.txt")
print(f.read())
f.close()
open()函数打开后,一直处于打开状态,需要手工关闭,使用with结构不用再,手动关闭文件。
with open("test.txt") as f:
print(f.read())
- r 以只读方式打开文件
- r+ 文件开头 覆盖开头原有的内容
- w w+ 文件开头 已存在的内容 会完全清空
- a a+ 文件末尾 已经存在的内容 不会清空
![cf3916da65486f70ad2cc37c8cfbf537.png](https://img-blog.csdnimg.cn/img_convert/cf3916da65486f70ad2cc37c8cfbf537.png)
- 读取-允许从文件读取
- 写-允许写入文件
- 创建-如果尚不存在则创建文件
- 截断-在打开文件期间将其清空(删除了文件的所有内容)
- 开始位置-打开文件后,初始位置设置为文件的开始
- 末尾位置-打开文件后,将初始位置设置为文件末尾
![9b241f1b5820a3a166e54be783b91697.png](https://img-blog.csdnimg.cn/img_convert/9b241f1b5820a3a166e54be783b91697.png)
读取文件
- read(): 读取整个文件,返回的是一个字符串
- readline():每次读取下一行文件,返回的是一个字符串
- readlines():一次性读取所有行文件。返回的是列表list
readlines()方法
逐行读取要用到 readlines()方法,当每次调用这个方法的时候,将会把文本中的每一行作为一个元素放在list中,返回包含了所有行的list。
file = open('test.txt', 'r')
print(file.readlines())
如果需要指定打出第2行,那么代码如下:
file = open('test.txt', 'r')
print(file.readlines()[3])
readline()方法
该方法每次读出一行内容,该方法返回字符串。
f = open("test.txt")
line = f.readline()
while line:
print (line)
line = f.readline()
f.close()
使用for循环逐行打开文件
file = open('test.txt', 'r')
for line in file:
print(line)
写入文件
写入需要用到write()方法, 模式mode不能使用 'r'
file = open('test.txt', 'w')
file.write('This is a test')
file.write(output+'n') #增加换行
file.close()
如何输出到文件
在 print()
函数中指定 file
关键字参数
doc=open('test.txt'.'w')
for i in range(0,5):
print(i)
print(i,file=doc)
doc.close()
with open('test.txt','wt') as f:
print('Hello World!', file=f)