Python文件操作:如何正确读写CSV文件
在Python中,我们可以使用内置的csv模块来读写CSV文件。以下是一些基本步骤:
- 读取CSV文件:
```python
import csv
with open(‘filename.csv’, newline=’’) as file:
reader = csv.reader(file)
for row in reader:
print(row)
这里,`'filename.csv'`是你要读取的CSV文件名。`newline=''`是用于处理不同操作系统下换行符的问题。
2. **写入CSV文件**:
```python
import csv
data_to_write = ['Column1', 'Column2', 'Column3'],
[value1, value2, value3] for row in data_to_write
with open('new_filename.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data_to_write)
这里,我们首先定义了要写入的列和数据。然后使用csv.writer函数创建一个写入器,最后调用writerow或writerows方法来写入数据。
注意:在读取或写入CSV文件时,需要确保提供的路径是有效的,并且有足够的权限来操作该文件。
还没有评论,来说两句吧...