Home >Backend Development >Python Tutorial >How Can I Write a Python List to a File with Newlines Between Each Item?
When writing a list to a file using Python, it's common to encounter the issue of not inserting newline characters. The writelines() method can be used to write a list of items to a file, but it does not automatically add newlines between them. To resolve this issue, a more elaborate approach is required.
One method involves using a loop to iterate over each line in the list and writing it to the file along with a newline character:
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)
Additionally, for Python 2, the following syntax was also available:
with open('your_file.txt', 'w') as f: for line in lines: print >> f, line
If you prefer a single function call, you can optimize it by removing square brackets from the list, allowing for the individual strings to be written one at a time:
with open('your_file.txt', 'w') as f: f.writelines(f"{line}\n" for line in lines)
The above is the detailed content of How Can I Write a Python List to a File with Newlines Between Each Item?. For more information, please follow other related articles on the PHP Chinese website!