Python文件內(nèi)容按行讀取到列表中
示例文件內(nèi)容如下:
Hello
World
Python
通常來(lái)講,我們?nèi)绻皇堑募?duì)象每一行颜阐,并做一些處理跪解,是不需要將文件對(duì)象轉(zhuǎn)成列表的,因?yàn)槲募?duì)象本身可迭代楷兽,而且是按行迭代:
with open('somefile', 'r') as f:
for line in f:
print(line, end='')
"""
Hello
World
Python
"""
轉(zhuǎn)換為列表進(jìn)行操作
- 包含換行符
- 方式一
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結(jié)果都是沒(méi)有去掉每一行行尾的換行符的(somefile.txt文件中最后一行本來(lái)就沒(méi)有換行符)
- 去掉換行符
- 方式一
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結(jié)果都是去掉每一行行尾的換行符
- 去掉行首行尾的空白字符
with open('somefile','r') as f:
content = [line.strip() for line in f]
print(content)
按行讀取文件內(nèi)容并得到當(dāng)前行號(hào)
文件對(duì)象是可迭代的(按行迭代)拄养,使用enumerate()即可在迭代的同時(shí)离斩,得到數(shù)字索引(行號(hào)),enumerate()的默認(rèn)數(shù)字初始值是0,如需指定1為起始瘪匿,可以設(shè)置其第二個(gè)參數(shù):
with open('somefile', 'r') as f:
for number, line in enumerate(f,start=1):
print(number, line, end='')
"""
1 Hello
2 World
3 Python
"""