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 """





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM