Friday, October 4, 2019

python - Correct way to write line to file?



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?


Answer



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:




No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...