Python 檔案內容按行讀取到列表中的方法

2021-10-08 07:24:58 字數 1593 閱讀 5411

示例檔案內容如下:

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)

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檔案中最後一行本來就沒有換行符)

方式一

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結果都是去掉每一行行尾的換行符

去掉行首行尾的空白字元

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

"""

出處: >

python按行讀取檔案

讀 1 2 3 4 file open sample.txt forline in file pass do something file.close 去除換行符 1 2 3 forline in file.readlines line line.strip n pass do something ...

按行讀取檔案

const string strurlfilename testurl.txt ifstream fin strurlfilename.c str fstream binary if fin fin.eof string serverurl getline fin,serverurl info lo...

python 按行讀取並判斷按行寫入檔案

f open description opinion.json w encoding utf 8 forline inopen test1set raw search.test1.json encoding utf 8 if question type description fact or opi...