Python將文件讀入列表


讀取日志文件的Python示例,一行一行地進入列表。

# With '\n', ['1\n', '2\n', '3']
with open('/www/logs/server.log') as f:
    content = f.readlines()
# No '\n', ['1', '2', '3']
with open('/www/logs/server.log') as f:
    content = f.read().splitlines()

1.讀取文件->列表

1.1虛擬日志文件

d:\\server.log 

a
b
c
d
1
2
3

包含1.2 \n   

filename = "d:\\server.log"
with open(filename) as f:
    lines = f.readlines()
print(type(lines))
print(lines)

輸出量

<class 'list'>
['a\n', 'b\n', 'c\n', 'd\n', '1\n', '2\n', '3']

1.3 \n排除在外

filename = "d:\\server.log"
with open(filename) as f:
    lines = f.read().splitlines()
print(type(lines))
print(lines)

輸出量

<class 'list'>
['a', 'b', 'c', 'd', '1', '2', '3']

 

  

 

 

  


免責聲明!

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



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