示例文件內容如下:
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 """