0

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
Deano
  • 11,582
  • 18
  • 69
  • 119

5 Answers5

2

os.system returns the exit status-code of the command, not its output.

Instead, you should use Python built-in open:

with open('file.txt') as f:
     list_of_lines = f.readlines()
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

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.

dohvis
  • 164
  • 2
  • 7
1

From the 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.

You should probably just open the file and readlines(). This SO question perfectly demonstrates this.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75
1

os.system returns exit status as integer, so that's why You get this error. Instead of using os.system, I suggest You read file using open command. Something like this:

input_file = open(filename)
for line in input_file.readlines():
    do_something()
Fejs
  • 2,734
  • 3
  • 21
  • 40
1

The os.system function does not return the output of the command you run, but an exit code. From the documentation:

the return value is the exit status of the process

If you want to get the content of a file, use open and close instead.

Right leg
  • 16,080
  • 7
  • 48
  • 81