Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print directly to a text file in both python 2.x and 3.x?

Instead of using write(), what are the other way to write to a text file in Python 2 and 3?

file = open('filename.txt', 'w')
file.write('some text')
like image 735
Ashwini Chaudhary Avatar asked May 04 '12 08:05

Ashwini Chaudhary


People also ask

How do you print to a text file in Python?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do you print two statements in Python?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3.

How do you write output to a file in Python?

#!/usr/bin/python import os,sys import subprocess import glob from os import path f = open('output. txt','w') sys. stdout = f path= '/home/xxx/nearline/bamfiles' bamfiles = glob. glob(path + '/*.


2 Answers

You can use the print_function future import to get the print() behaviour from python3 in python2:

from __future__ import print_function
with open('filename', 'w') as f:
    print('some text', file=f)

If you do not want that function to append a linebreak at the end, add the end='' keyword argument to the print() call.

However, consider using f.write('some text') as this is much clearer and does not require a __future__ import.

like image 162
ThiefMaster Avatar answered Sep 26 '22 23:09

ThiefMaster


f = open('filename.txt','w')

# For Python 3 use
print('some Text', file=f)

#For Python 2 use
print >>f,'some Text'
like image 40
Ashwini Chaudhary Avatar answered Sep 25 '22 23:09

Ashwini Chaudhary