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

Aug 3, 2018 in Python by bug_seeker
• 15,520 points
874 views

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,090 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
26,835 views
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
924 views
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 1,258 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,067 views
0 votes
1 answer
+5 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,790 points
3,488 views
0 votes
1 answer

Best way to create a simple python web service

web.py is probably the simplest web framework ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 58,090 points
688 views
+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,210 points
721 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP