Writing a List to a File with Python, Including Newlines
To write a list to a file while inserting newlines, there are several approaches to consider.
Using a Loop:
This method involves iterating through the list and writing each line to the file with a newline character added.
with open('your_file.txt', 'w') as f: for line in lines: f.write(f"{line}\n")
For Python <3.6:
In earlier versions of Python, use the following syntax:
with open('your_file.txt', 'w') as f: for line in lines: f.write("%s\n" % line)
For Python 2:
For Python 2, this approach is also viable:
with open('your_file.txt', 'w') as f: for line in lines: print >> f, line<p><strong>Using a List Comprehension (Efficient):</strong></p> <p>To avoid creating an unnecessary intermediate list, remove the square brackets [] in the list comprehension. This produces a generator expression instead, which is more memory-efficient.</p> <pre class="brush:php;toolbar:false">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?. For more information, please follow other related articles on the PHP Chinese website!