2016-11-09 79 views
0

我想要的file.txt内容保存到列表从OS命令python创建列表

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 

回答

2

如果要返回命令输出,请使用popen而不是os.system

import subprocess 

proc = subprocess.Popen(["cat", "file.txt"], stdout=subprocess.PIPE, shell=True) 
(out, err) = proc.communicate() 
print "output:", out 

但我认为@Fejs的答案是更好的。

1

来自docs

os.system(command)
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

您应该只需open该文件和readlines()This这个问题很好地证明了这一点。

2

os.system返回命令的退出状态代码,而不是其输出。

相反,你应该使用Python内置open:作为整数

with open('file.txt') as f: 
    list_of_lines = f.readlines() 
1

os.system返回退出状态,所以这就是为什么你得到这个错误。而不是使用os.system,我建议你使用open命令读取文件。 事情是这样的:

input_file = open(filename) 
for line in input_file.readlines(): 
    do_something() 
1

os.system函数不返回运行该命令的输出,但退出代码。从documentation

the return value is the exit status of the process

如果你想获得一个文件的内容,使用openclose代替。