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