python写入列表txt文件
时间: 2023-08-19 17:14:37 浏览: 129
Python打开文件,将list、numpy数组内容写入txt文件中的方法
你可以使用以下几种方法将Python中的列表写入到txt文件中:
方法一:使用writelines()函数直接写入列表
```python
list = \[1, 2, 3, 4, 'liyaya'\]
with open('1.txt', 'w') as f:
f.writelines(str(i) + '\n' for i in list)
```
方法二:将列表转化为字符串再写入
```python
list = \[1, 2, 3, 4, 'liyaya'\]
str_list = \[str(i) for i in list\]
with open('1.txt', 'w') as f:
f.write('\n'.join(str_list))
```
方法三:使用for循环逐行写入
```python
list = \[1, 2, 3, 4, 'liyaya'\]
with open('1.txt', 'w') as f:
for i in list:
f.write(str(i) + '\n')
```
方法四:使用for循环逐行写入,效果展示如下:
```python
l = \["A", "B", "C", "D"\]
with open("k.txt", "w") as f:
for line in l:
f.write(line + '\n')
```
以上是几种常用的将Python列表写入txt文件的方法,你可以根据自己的需求选择其中一种方法来实现。
#### 引用[.reference_title]
- *1* [python中将列表内容写入txt文档](https://blog.csdn.net/liyayaa/article/details/127217546)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [[python]---list列表写入txt文档的多种方法](https://blog.csdn.net/weixin_45699912/article/details/117328629)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文