Deano Deano - 28 days ago 18
Python Question

create list from os command python

I'm trying to store content of

file.txt
into list

cat file.txt
dm-3
dm-5
dm-4
dm-2


here is my script:

#!/usr/bin/python
import os
import json
drives = os.system("cat file.txt")
for i in drives:
print(i)


I'm getting the following error:

Traceback (most recent call last):
File "./lld-disks2.py", line 5, in <module>
for i in drives:
TypeError: 'int' object is not iterable

Answer

If you want to return of command output, use popen instead os.system.

import subprocess

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

But I think @Fejs's answer is better.