Python3基础之(十 七)读写文件3

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/PoGeN1/article/details/84138073

一、读取文件内容 file.read()

上一节我们讲了,写文件用的是'w''a',那么今天来看看读取文件怎么做
使用 file.read() 能够读取到文本的所有内容.

if __name__=='__main__':
    file=open('my file.txt','r')
    content=file.read()
    print(content)

我们可以看出,无论是读取还是写入,都需要先将文件open一下,只不过读的时候后面参数是'r',写的时候后面参数是'w'或者'a'

二、按行读取 file.readline()

如果想在文本中一行行的读取文本, 可以使用 file.readline(), file.readline()读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:

file= open('my file.txt','r') 
content=file.readline()  # 读取第一行
print(content)

""""
This is my first test.
""""

second_read_time=file.readline()  # 读取第二行
print(second_read_time)

"""
This is the second line.
"""

三、读取所有行 file.readlines()

如果想要读取所有行, 并可以使用像 for 一样的迭代器迭代这些行结果, 我们可以使用 file.readlines(), 将每一行的结果存储在 list 中, 方便以后迭代.

file= open('my file.txt','r') 
content=file.readlines() # python_list 形式
print(content)

""""
['This is my first test.\n', 'This is the second line.\n', 'This the third line.\n', 'This is appended file.']
""""

# 之后如果使用 for 来迭代输出:
for item in content:
    print(item)
    
"""
This is my first test.

This is the second line.

This the third line.

This is appended file.
"""

猜你喜欢

转载自blog.csdn.net/PoGeN1/article/details/84138073