Correct way to write line to file

0 votes

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" this universal or Unix-specific? IE, should I be doing "\r\n" on Windows?

Aug 3, 2018 in Python by bug_seeker
• 15,550 points

1 answer to this question.

0 votes

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:

os (particularly os.linesep)

answered Aug 3, 2018 by Priyaj
• 58,120 points

Related Questions In Python

+1 vote
4 answers

How to write nested dictionaries to a CSV file

Using DictWriter there is no need in ...READ MORE

answered Oct 18, 2018 in Python by Richard William
0 votes
1 answer

How can I write nested dictionaries to a csv file?

You can use the pandas library to ...READ MORE

answered Apr 17, 2018 in Python by anonymous
0 votes
1 answer

What's the right way to concatenate files and appending the New Line character in Python? Text or binary mode?

It seems like you're using the wrong ...READ MORE

answered Nov 13, 2018 in Python by Anirudh
• 2,080 points

edited Dec 14, 2018 by Anirudh 515 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,059 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
1 answer

Best way to create a simple python web service is probably the simplest web framework ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 58,120 points
+1 vote
2 answers

Appending data to a file

First open the file that you want ...READ MORE

answered Jul 23, 2018 in Python by Omkar
• 69,130 points