How to redirect 'print' output to a file?
The most obvious way to do this would be to print to a file object:
with open('out.txt', 'w') as f:
print('Filename:', filename, file=f) # Python 3.x
print >> f, 'Filename:', filename # Python 2.x
However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:
import sys
orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f
for i in range(2):
print('i = ', i)
sys.stdout = orig_stdout
f.close()
Since Python 3.4 there's a simple context manager available to do this in the standard library:
from contextlib import redirect_stdout
with open('out.txt', 'w') as f:
with redirect_stdout(f):
print('data')
Redirecting externally from the shell itself is another option, and often preferable:
./script.py > out.txt
Other questions:
What is the first filename in your script? I don't see it initialized.
My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.
Also, use os.path.join and os.path.basename to manipulate paths and filenames.
Directing print output to a .txt file
Give print
a file
keyword argument, where the value of the argument is a file stream. The best practice is to open the file with the open
function using a with
block, which will ensure that the file gets closed for you at the end of the block:
with open("output.txt", "a") as f:
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
From the Python documentation about print
:
The
file
argument must be an object with awrite(string)
method; if it is not present orNone
,sys.stdout
will be used.
And the documentation for open
:
Open
file
and return a corresponding file object. If the file cannot be opened, anOSError
is raised.
The "a"
as the second argument of open
means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead at the beginning of the with
block, use "w"
.
The with
block is useful because, otherwise, you'd need to remember to close the file yourself like this:
f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()
Redirecting function output to text file
Someone has already shared the link to the top answer on redirecting stdout but you haven't picked up on the part in that answer that might help.
from contextlib import redirect_stdout
with open('log.txt', 'w') as f:
with redirect_stdout(f):
my_function() #Call your function here any prints will go to the file
print("This text") #This will be output to the file too
This will temporarily redirect the output of print to the log.txt file.
Python: How to redirect print output to txt file?
You can do that by using providing file proxy in the file parameter of print function.
For example,
f = open('temp.txt' , 'w')
print('a' , file = f)
f.close()
Here,I redirected string 'a' in the file 'temp.txt'.
How to redirect the output of print statement of (if-else) to a text file in Python
In Python3 the output redirection is as simple as
print(....., file = open("filename",'w'))
Refer the docs
In your particular case you can even use the with open
syntax as in
if(cp<0):
print("No Common Predecessor")
elif (posa < posb):
if(posa<0):
posa=0
with open('out.txt','w')as f:
print("Common Predecessor: %s" %n[posa])
f.write("Common Predecessor: %s" %n[posa])
else:
if(posb < 0):
posb=0
with open('anotherout.txt','w')as f:
print("Common Predecessor: %s" %m[posb])
f.write("Common Predecessor: %s" %m[posb])
Note - It is always better to use 'a'
(append) instead of 'w'
incase you are re-executing the program.
Redirect C output to a txt file
The user input is stdin
but you are redirecting only stdout
to file. Hence you will see in the output.txt
only what your program prints to stdout
. If you want to print entered values, you have to print them after scanf
.
In the example below, you should see also input values in your output.txt
printf("Enter float1: ");
scanf("%f", &float1);
printf("%f\n", float1);
How to redirect program output to text file
A good start is not ignoring compiler warnings:
test.c: In function ‘main’:
test.c:42:13: warning: passing argument 4 of ‘fwrite’ makes pointer from integer without a cast [enabled by default]
fwrite(c, 1, sizeof(c), output);
^
In file included from test.c:1:0:
/usr/include/stdio.h:715:15: note: expected ‘struct FILE * __restrict__’ but argument is of type ‘int’
extern size_t fwrite (const void *__restrict __ptr, size_t __size,
^
int
and FILE*
are not interchangable. If you use open
, write with write
. If you use fopen
, write with fwrite
.
Additionally, you never modify stdout of your process. Instead you modify output
, which doesn't make sense. Here are the minimum changes to your code to make it work:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd[2];
int processId;
int output;
char filename[] = "output.txt";
if((output = open(filename, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR)) == -1){
fprintf(stderr, "Unable to create/open file '%s'\n", filename);
return 1;
}
if(pipe(fd) == -1){
fprintf(stderr, "Error creating pipe\n");
return 2;
}
if((processId = fork()) == -1){
fprintf(stderr, "Error forking\n");
return 3;
}
if(processId == 0){
int newFD = dup(STDOUT_FILENO);
char newFileDescriptor[2];
sprintf(newFileDescriptor, "%d", newFD);
dup2(fd[1], STDOUT_FILENO); // You want to modify STDOUT_FILENO
close(fd[0]);
execl("/bin/echo", "echo", newFileDescriptor, NULL); // switched to echo
}else{
close(fd[1]);
char c[10];
int r = read(fd[0], c, sizeof(char) * 10);
if(r > 0){
fprintf(stderr, "PIPE INPUT = %s", c);
write(output, c, r); // use write instead of fwrite
}
}
}
Here's the result of running it:
$ gcc test.c -o test
$ ./test
PIPE INPUT = 6
$ cat output.txt
6
Redirect the output of python script into a text file
Just use standard shell redirection:
python your_script.py > output_file.ext
If you want to write to a file directly from the script without redirecting:
with open("output.ext", "w") as stream:
print >>stream, "text"
Related Topics
How to Copy Over an Excel Sheet to Another Workbook in Python
Replace Nth Occurrence of Substring in String
Truncate to Three Decimals in Python
Why Can't Environmental Variables Set in Python Persist
Overriding "+=" in Python? (_Iadd_() Method)
Pygame How to Let Balls Collide
What's the Difference Between "Update" and "Update_Idletasks"
Is There a Simple Way to Change a Column of Yes/No to 1/0 in a Pandas Dataframe
How to Sort a List by Length of String Followed by Alphabetical Order
How to Compare Dates in Django Templates
How to Write Tests for the Argparse Portion of a Python Module
Appending Item to Lists Within a List Comprehension
Sphinx's Autodoc's Automodule Having Apparently No Effect
Difference Between Parsing a Text File in R and Rb Mode
What's the Cleanest Way to Extract Urls from a String Using Python