深度阅读

How do I write a list to a file in Python?

作者
作者
2023年08月22日
更新时间
20.97 分钟
阅读时间
0
阅读量

To write a list to a file in Python, you can use the with open() syntax to open a file and write each item in the list on a new line. Here’s an example:

my_list = ['item1', 'item2', 'item3']

with open('output.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

In this example, we first define a list called my_list. Next, we use the with open() syntax to open a file called output.txt in write mode, and then we use a for loop to iterate through each item in the list. At each iteration, we write the item to the file, followed by a newline character to ensure that each item is on a new line.

After running the above code, a file called output.txt will be created in the same directory as your Python script, and it will contain each item in my_list on its own line.

Note that if your list contains items that are not strings, you may need to convert them to strings using str() before writing them to the file. Additionally, you can customize the output format by changing the format string passed to f.write().

here are multiple ways to write a list to a file in Python:

Method 1: Using a loop to write each item on a new line

my_list = ['item1', 'item2', 'item3']

with open('output.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

Method 2: Using the print() function with a file argument to write each item on a new line

my_list = ['item1', 'item2', 'item3']

with open('output.txt', 'w') as f:
    for item in my_list:
        print(item, file=f)

Method 3: Converting the list to a string and writing the whole string to the file

my_list = ['item1', 'item2', 'item3']

with open('output.txt', 'w') as f:
    f.write('\n'.join(my_list))

Keep in mind that if the list contains items that are not strings, you may need to convert them to strings before writing them to the file using str(). Additionally, you can customize the output format by changing the string format passed to f.write() or print().

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。