怎么把Python里面列表里面的元素输出到excl 和 TXT文档里面
时间: 2024-04-04 07:30:05 浏览: 112
你可以使用Python中的csv模块将列表中的元素输出到Excel和TXT文档中。下面是两种不同的方法:
1. 输出到Excel文件:
```python
import csv
data = [['Name', 'Age', 'City'],
['John', 28, 'New York'],
['Alice', 32, 'London'],
['Bob', 45, 'Paris']]
filename = 'output.csv'
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
print(f"Data has been written to {filename} successfully.")
```
2. 输出到TXT文件:
```python
data = ['apple', 'banana', 'orange', 'grape']
filename = 'output.txt'
with open(filename, 'w') as file:
for item in data:
file.write(f"{item}\n")
print(f"Data has been written to {filename} successfully.")
```
以上代码示例展示了如何将列表中的元素输出到相应的文件中。你可以根据自己的需求修改数据和文件名。
阅读全文