16

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

AndreP
  • 105
  • 1
  • 5
user2957951
  • 303
  • 2
  • 4
  • 11
  • 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. – user2357112 Feb 23 '14 at 02:47

8 Answers8

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);
Nick Beeuwsaert
  • 1,598
  • 1
  • 11
  • 18
  • 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! – user2957951 Feb 23 '14 at 02:30
  • are you using IDLE or in the command line? Usually you can select all the lines and paste it in either way – Nick Beeuwsaert Feb 23 '14 at 02:33
  • 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 :( – user2957951 Feb 23 '14 at 02:37
  • did you change "./script.py" to "./file.py" (or whatever you have named as the file you want to run)? – Nick Beeuwsaert Feb 23 '14 at 02:48
  • You're missing a colon on the `with` statement and a write mode on the `open` call. – user2357112 Feb 23 '14 at 02:48
  • Add that for each additional arguments you have to separate each of them by a comma (,). – Pushpa Jan 14 '20 at 01:01
5

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.

slfan
  • 8,950
  • 115
  • 65
  • 78
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
aknuds1
  • 65,625
  • 67
  • 195
  • 317
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.

Dibin Joseph
  • 251
  • 3
  • 6
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.

Remolten
  • 2,614
  • 2
  • 25
  • 29
  • 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 – user2957951 Feb 23 '14 at 02:53
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()
don
  • 186
  • 2
  • 15
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.

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

KowaiiNeko
  • 327
  • 6
  • 17