Writing a list to a file is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to write a list to a file efficiently.
Example 1:
fruits = ['apple', 'banana', 'orange', 'kiwi'] with open('fruits.txt', 'w') as file: for fruit in fruits: file.write(fruit + '\n')
Example 2:
numbers = [1, 2, 3, 4, 5] with open('numbers.txt', 'w') as file: file.write('\n'.join(map(str, numbers)))