user2825833
user2825833

Reputation: 57

How do I write to a file using a terminal command in python?

I am learning to code, Im very new. I have written a few scripts, and would like to combine them into a single script. I am essentially trying to take the "look ." command from terminal, input it into a text file, and then open that text file to begin manipulating the words inside of it.

I have tried many different variations:

print "What file do you want to create? "
file_in = raw_input(">")
file_in = open(file_in, 'w')
new_file = os.system("look .")
file_in.write(new_file)

This results in:

Traceback (most recent call last):
File "hash.py", line 13, in <module>
file_in.write(new_file)
TypeError: expected a character buffer object

After all of the words are printed to screen.

I have also tried this:

print "What file do you want to create? "
file_in = raw_input(">")
new_file = os.system("look . > "+file_in+".txt")

##This is attempting to open the file to make each word capital in the list, the list is     made at this point
capital_words=open(new_file, 'w')

But this results in:

capital_words = open(new_file, 'w')
TypeError: coercing to Unicode: need string or buffer, int found

I have tried converting the capital_words to str. But it simply will not let me do this. I can make the list using a script, and I can open an existing list and capitalize each word (which is what I am intending to do here) using a separate script, but I get this problem when I combine them.

Any help is appreciated.

(I know this doesnt have any practical application, Im just trying to learn the basics of programming)

Upvotes: 1

Views: 279

Answers (1)

MrD
MrD

Reputation: 2455

The os.system call doesn't return the output of the program you called. It returns its exit code. To capture the output of a program you need to use the subprocess module, call Popen and capture the output with subprocess.PIPE.

Here's how:

import subprocess
# Create a Popen object that captures the output.
p=subprocess.Popen(['look','data'],stdout=subprocess.PIPE)
# Call 'look data' and wait for it to finish.
p.wait()
# Now read the output.
print p.stdout.read()

This will produce:

data
database
database's
databases

To dump the output to a file, instead of print p.stdout.read() you should do something like this:

import subprocess
with open('foobar.txt', 'w') as f:
  p=subprocess.Popen(['look','data'], stdout=f)
  p.wait()

Upvotes: 1

Related Questions