python3 读取csv
时间: 2023-09-30 07:03:35 浏览: 86
python3读取csv和xlsx文件的实例
要在Python3中读取CSV文件,你可以使用csv模块。以下是一个示例代码:
```python
import csv
filename = 'lagou.csv'
data = \[\]
try:
with open(filename, encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader)
data = \[row for row in reader\]
except csv.Error as e:
print("Error reading CSV file at line %s:%s" % (reader.line_num, e))
sys.exit(-1)
if header:
print(header)
print("===============")
for datarow in data:
print(datarow)
```
这段代码首先打开CSV文件,然后使用csv.reader()函数创建一个reader对象。接下来,我们可以使用for循环遍历reader对象,逐行读取CSV文件中的数据并打印出来。在这个例子中,我们还打印了CSV文件的标题行(header)和数据行(data)。请注意,你需要将文件名替换为你实际使用的CSV文件的名称。\[1\]
#### 引用[.reference_title]
- *1* [Python3读取CSV数据](https://blog.csdn.net/weixin_45890771/article/details/120382819)[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^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [python3:csv的读写](https://blog.csdn.net/a13568hki/article/details/121977445)[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^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [python3读写csv文件](https://blog.csdn.net/weixin_30883311/article/details/99869412)[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^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文