Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to write line to file?

Tags:

python

file-io

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?

Update: Regarding all those answers with "\n"...is this universal or Unix-specific? IE, should I be doing "\r\n" on Windows?

like image 558
Yaroslav Bulatov Avatar asked May 28 '11 05:05

Yaroslav Bulatov


People also ask

How do you write one line in Python?

Python writes a line to file. To write a line to a file in Python, use a with open() function. The with statement helps you to close the file without explicitly closing it.


1 Answers

This should be as simple as:

with open('somefile.txt', 'a') as the_file:     the_file.write('Hello\n') 

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Some useful reading:

  • The with statement
  • open()
    • 'a' is for append, or use
    • 'w' to write with truncation
  • os (particularly os.linesep)
like image 193
Johnsyweb Avatar answered Sep 23 '22 10:09

Johnsyweb