python 读取文件函数
读取文件内容 file.read()
使用 file.read() 能够读取到文本的所有内容.
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() 读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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.
"""
本文来自博客园,作者:I'm_江河湖海,转载请注明原文链接:https://www.cnblogs.com/jhhh/p/16761046.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了