Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm used to doing print >>f, "hi there"

However, it seems that print >> is getting deprecated. What is the recommended way to do the line above?

1 Answer

0 votes
by (106k points)
edited by

To write a line to a file you should use the print() function which is available since the release of  Python 2.6+:-

from __future__ import print_function # Only needed for Python 2 

print("hi there", file=f)

In Python 3 we have print() function as default so we don't need the import it:-

f = open('myfile', 'w')

f.write('hi there\n') # python will convert \n to os.linesep f.close() # you can omit in most cases as the destructor will call it

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...