python将列表写入txt文件
时间: 2023-05-10 07:55:20 浏览: 89
可以使用以下代码将 Python 列表写入 txt 文件:
```
my_list = [1, 2, 3, 4, 5]
with open('my_file.txt', 'w') as f:
for item in my_list:
f.write("%s\n" % item)
```
这将把列表中的每个元素写入 txt 文件中,每个元素占一行。
相关问题
python将列表写入txt文件并覆盖原来的内容
你可以使用Python内置的文件操作函数来实现将列表写入txt文件并覆盖原来的内容。具体实现步骤如下:
1. 打开txt文件,使用“w”模式表示以写入的方式打开文件,如果文件不存在则创建文件:
```
with open("file.txt", "w") as f:
```
2. 将列表转换为字符串,使用“\n”作为每个元素之间的分隔符:
```
list = ["apple", "banana", "orange"]
content = "\n".join(list)
```
3. 将字符串写入txt文件:
```
f.write(content)
```
4. 关闭文件:
```
f.close()
```
完整代码如下:
```
list = ["apple", "banana", "orange"]
content = "\n".join(list)
with open("file.txt", "w") as f:
f.write(content)
f.close()
```
执行完以上代码后,原来的txt文件内容将被覆盖为"apple\nbanana\norange"。
python将列表写入txt
可以使用Python中的文件操作,将列表写入txt文件中,方法如下:
```python
# 定义一个列表
my_list = ['apple', 'banana', 'orange', 'pear']
# 打开要写入的txt文件
with open('my_list.txt', 'w') as f:
# 将列表中的每个元素写入文件中,每个元素占一行
for item in my_list:
f.write("%s\n" % item)
```
执行以上代码后,会在当前目录下生成一个名为`my_list.txt`的文件,文件中包含了`my_list`列表中的每个元素。