Home >Backend Development >Python Tutorial >How to Write a List to a File with Newlines in Python?
In Python, the 'writelines()' method doesn't automatically insert newlines when writing a list to a file. To circumvent this issue, an alternative solution is to iterate through the list and write each element with a newline character appended:
with open('your_file.txt', 'w') as f: for line in lines: f.write(f"{line}\n")
Prior to Python 3.6, the following syntax was used:
with open('your_file.txt', 'w') as f: for line in lines: f.write("%s\n" % line)
Alternatively, for Python 2, the 'print' function can be utilized:
with open('your_file.txt', 'w') as f: for line in lines: print >> f, line
While it's possible to perform this task with a single function call, it's recommended to remove the square brackets around the list to ensure that the strings are written sequentially, rather than creating an entire list in memory first.
The above is the detailed content of How to Write a List to a File with Newlines in Python?. For more information, please follow other related articles on the PHP Chinese website!