17

I'm executing a .py file, which spits out a give string. This command works fine

execfile ('file.py')

But I want the output (in addition to it being shown in the shell) written into a text file.

I tried this, but it's not working :(

execfile ('file.py') > ('output.txt')

All I get is this:

tugsjs6555

False

I guess "False" is referring to the output file not being successfully written :(

Thanks for your help

1
  • Do you really want to run file.py in the current scope, with access to all the variables and such you have defined, or do you want to run it in its own separate environment? execfile is most likely not the tool you should be using. Commented Feb 23, 2014 at 2:47

8 Answers 8

17

what your doing is checking the output of execfile('file.py') against the string 'output.txt'

you can do what you want to do with subprocess

#!/usr/bin/env python
import subprocess
with open("output.txt", "w+") as output:
    subprocess.call(["python", "./script.py"], stdout=output);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks raser, but how am I suppose to run this in the >>> ?? I tried writing one line at a time, but when I try the 2nd line I get a syntax error :( Can you please dumb it down for me ;) Cheers!
are you using IDLE or in the command line? Usually you can select all the lines and paste it in either way
I'm a newbie to python and have just installed python27 on my win8. so I'm using cmd. I've tried c/p the above code onto a new file, saved it as run.py and tried execfile ('run.py'), but still didn't work :(
did you change "./script.py" to "./file.py" (or whatever you have named as the file you want to run)?
You're missing a colon on the with statement and a write mode on the open call.
|
6

If you are running the file on Windows command prompt:

python filename.py >> textfile.txt

The output would be redirected to the textfile.txt in the same folder where the filename.py file is stored.

The above is only if you have the results showing on cmd and you want to see the entire result without it being truncated.

Comments

4

This'll also work, due to directing standard out to the file output.txt before executing "file.py":

import sys

orig = sys.stdout
with open("output.txt", "wb") as f:
    sys.stdout = f
    try:
        execfile("file.py", {})
    finally:
        sys.stdout = orig

Alternatively, execute the script in a subprocess:

import subprocess

with open("output.txt", "wb") as f:
    subprocess.check_call(["python", "file.py"], stdout=f)

If you want to write to a directory, assuming you wish to hardcode the directory path:

import sys
import os.path

orig = sys.stdout
with open(os.path.join("dir", "output.txt"), "wb") as f:
    sys.stdout = f
    try:
        execfile("file.py", {})
    finally:
        sys.stdout = orig

9 Comments

Unless file.py tries to do something with a variable named orig or messes with your code in some other way.
True, I've edited my code to pass a separate globals dictionary.
Bingo! You Got It :) Thanks A Million! Now is there a way to choose a different dir where to write out the output file? Cheers!
What's the point of using check_call if you aren't catching it, in that oddly familiar looking bit of code?
@raser It's better to have a fatal exception, than to swallow an eventual error.
|
2

The simplest way to run a script and get the output to a text file is by typing the below in the terminal:

PCname:~/Path/WorkFolderName$ python scriptname.py>output.txt

*Make sure you have created output.txt in the work folder before executing the command.

Comments

1

Use this instead:

text_file = open('output.txt', 'w')
text_file.write('my string i want to put in file')
text_file.close()

Put it into your main file and go ahead and run it. Replace the string in the 2nd line with your string or a variable containing the string you want to output. If you have further questions post below.

1 Comment

Thanks Rem, This worked BUT it only writes out whatever string you write instead of "my string i want to put in file". What goes there in the real script file.py, which returns the actual string that I want written onto the output.txt file :( I think this will work if we assign the output of file.py to a variable, then use that var instead...any idea how to do that? THX
0
file_open = open("test1.txt", "r")
file_output = open("output.txt", "w")

for line in file_open:
    print ("%s"%(line), file=file_output)

file_open.close()
file_output.close()

1 Comment

@user2957951: please always mention the error to the person so that he can help you further on with higher chance.
0

using some hints from Remolten in the above posts and some other links I have written the following:

from os import listdir
from os.path import isfile, join
folderpath = "/Users/nupadhy/Downloads"
filenames = [A for A in listdir(folderpath) if isfile(join(folderpath,A))]
newlistfiles = ("\n".join(filenames))
OuttxtFile = open('listallfiles.txt', 'w')
OuttxtFile.write(newlistfiles)
OuttxtFile.close()

The code above is to list all files in my download folder. It saves the output to the output to listallfiles.txt. If the file is not there it will create and replace it with a new every time to run this code. Only thing you need to be mindful of is that it will create the output file in the folder where your py script is saved. See how you go, hope it helps.

Comments

0

You could also do this by going to the path of the folder you have the python script saved at with cmd, then do the name.py > filename.txt It worked for me on windows 10

2 Comments

It would be great if you could provide some verifiable code to support the answer.
D:\Python\Python3> scrap.py > results.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.