Answers for "how to write newline to file in python"

1

python write to text file with new line

# This will open a new file called myFile.txt and 
# write 0 - 4 using a loop, each on a new line.
# Note the "\n" part!

with open("myFile.txt", "w") as file:
  for i in range(0,5):
    file.write(str(i) + "\n")

# We do not need to use "file.close()" because 
# we used "with open(...)" which is considered 
# to be more "pythonic"
Posted by: Guest on March-04-2022
4

python writelines newline

lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.writelines("%s\n" % l for l in lines)
Posted by: Guest on October-19-2020

Code answers related to "how to write newline to file in python"

Python Answers by Framework

Browse Popular Code Answers by Language