python按⾏读取txt⽂件-Python⽂件内容按⾏读取到列表中Python⽂件内容按⾏读取到列表中
⽰例⽂件内容如下:
Hello
World
Python
通常来讲,我们如果只是迭代⽂件对象每⼀⾏,并做⼀些处理,是不需要将⽂件对象转成列表的,因为⽂件对象本⾝可迭代,⽽且是按⾏迭代:
with open('somefile', 'r') as f:
for line in f:
print(line, end='')
"""
Hello
World
Python
"""
转换为列表进⾏操作
包含换⾏符
⽅式⼀
with open('somefile','r') as f:
content = list(f)
python怎么读取py文件print(content)
"""
['Hello ', 'World ', 'Python']
"""
⽅式⼆
with open('somefile','r') as f:
content = f.readlines()
print(content)
"""
['Hello ', 'World ', 'Python']
"""
其中,content结果都是没有去掉每⼀⾏⾏尾的换⾏符的(⽂件中最后⼀⾏本来就没有换⾏符)
去掉换⾏符
⽅式⼀
with open('somefile','r') as f:
content = f.read().splitlines()
print(content)
"""
['Hello', 'World', 'Python']
"""
⽅式⼆
with open('somefile','r') as f:
content = [line.rstrip(' ') for line in f]
print(content)
"""
['Hello', 'World', 'Python']
"""
其中,content结果都是去掉每⼀⾏⾏尾的换⾏符
去掉⾏⾸⾏尾的空⽩字符
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
"""

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。