python程序如何将print的结果输入到一个csv表里面
时间: 2024-01-21 08:18:56 浏览: 37
可以使用Python内置的csv模块将print的结果写入csv表中。
首先,需要导入csv模块:
```python
import csv
```
然后,打开一个csv文件并创建一个csv写入器:
```python
with open('output.csv', mode='w', newline='') as file:
writer = csv.writer(file)
```
其中,`output.csv`是你要写入的csv文件名。`mode='w'`表示以写模式打开文件,如果文件不存在则自动创建。`newline=''`表示使用默认的行结束符。
接下来,可以将print的结果写入csv文件中:
```python
print('hello, world!')
writer.writerow(['hello', 'world'])
```
这里我们同时使用了print和writerow函数,将同样的结果写入到控制台和csv文件中。`writerow`函数接受一个列表作为参数,每个元素都被写入到csv文件的一列中。
完整代码如下:
```python
import csv
with open('output.csv', mode='w', newline='') as file:
writer = csv.writer(file)
print('hello, world!')
writer.writerow(['hello', 'world'])
```
运行该程序后,将在控制台输出`hello, world!`,并在`output.csv`文件中写入一行数据`hello,world`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)