我正在尝试将file.txt的内容存储到列表中
cat file.txt
dm-3
dm-5
dm-4
dm-2这是我的剧本:
#!/usr/bin/python
import os
import json
drives = os.system("cat file.txt")
for i in drives:
print(i)我得到了以下错误:
Traceback (most recent call last):
File "./lld-disks2.py", line 5, in <module>
for i in drives:
TypeError: 'int' object is not iterable发布于 2016-11-09 11:52:04
如果您想返回命令输出,请使用popen而不是os.system。
import subprocess
proc = subprocess.Popen(["cat", "file.txt"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "output:", out但我认为@Fejs的答案更好。
发布于 2016-11-09 11:19:43
os.system返回命令的退出状态代码,而不是它的输出。
相反,您应该使用内置的open。
with open('file.txt') as f:
list_of_lines = f.readlines()https://stackoverflow.com/questions/40505700
复制相似问题