Python文件内容按行读取到列表中

Python文件内容按行读取到列表中

示例文件内容如下:

Hello
World
Python

通常来讲,我们如果只是迭代文件对象每一行,并做一些处理,是不需要将文件对象转成列表的,因为文件对象本身可迭代,而且是按行迭代:

with open('somefile', 'r') as f:
    for line in f:
        print(line, end='')
        
"""
Hello
World
Python
"""

转换为列表进行操作

  1. 包含换行符
  • 方式一
with open('somefile','r') as f:
    content = list(f)
    print(content)
"""
['Hello\n', 'World\n', 'Python']
"""
  • 方式二
with open('somefile','r') as f:
    content = f.readlines()
    print(content)
"""
['Hello\n', 'World\n', 'Python']
"""    

其中,content结果都是没有去掉每一行行尾的换行符的(somefile.txt文件中最后一行本来就没有换行符)

  1. 去掉换行符
  • 方式一
with open('somefile','r') as f:
    content = f.read().splitlines()
    print(content)
"""
['Hello', 'World', 'Python']
"""
  • 方式二
with open('somefile','r') as f:
    content = [line.rstrip('\n') for line in f]
    print(content)
"""
['Hello', 'World', 'Python']
"""    

其中,content结果都是去掉每一行行尾的换行符

  1. 去掉行首行尾的空白字符
with open('somefile','r') as f:
    content = [line.strip() for line in f]
    print(content)

按行读取文件内容并得到当前行号

文件对象是可迭代的(按行迭代),使用enumerate()即可在迭代的同时,得到数字索引(行号),enumerate()的默认数字初始值是0,如需指定1为起始,可以设置其第二个参数:

with open('somefile', 'r') as f:
    for number, line in enumerate(f,start=1):
        print(number, line, end='')
"""
1 Hello
2 World
3 Python
"""

参考博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • .bat脚本基本命令语法 目录 批处理的常见命令(未列举的命令还比较多,请查阅帮助信息) 1、REM 和 :: 2...
    庆庆庆庆庆阅读 8,184评论 1 19
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,435评论 0 5
  • 项目测试阶段,出现难以定位的问题时,需要我们导出我们测试同事手机中的崩溃日志,以及后期苹果审核被拒后返回的崩溃日志...
    swluan阅读 887评论 0 1
  • 1.安装eclipse 内存分析工具:eclipse memory analyzer 2.eclipse memo...
    ddxueyu阅读 481评论 0 1
  • 老百姓说的"拉肚子",指的就是腹泻,西医的教科书上有很多分类,根据发病时间长短分,有急性和慢性;根据病因分,有炎症...
    经济的草根阅读 1,496评论 6 96