前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 读取文件函数

python 读取文件函数

作者头像
演化计算与人工智能
发布2020-08-14 10:27:30
4880
发布2020-08-14 10:27:30
举报

读取文件内容 file.read()

  • 使用 file.read() 能够读取到文本的所有内容.
代码语言:javascript
复制
file= open('my file.txt','r')
content=file.read()
print(content)

""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""

按行读取 file.readline()

  • 如果想在文本中一行行的读取文本, 可以使用 file.readline(), file.readline() 读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:
代码语言:javascript
复制
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 中, 方便以后迭代.
代码语言:javascript
复制
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.
"""
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DrawSky 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 读取文件内容 file.read()
  • 按行读取 file.readline()
  • 读取所有行 file.readlines()
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档