python怎么读取csv文件
时间: 2023-08-12 20:08:32 浏览: 105
要使用Python读取CSV文件,可以使用标准库CSV提供的函数。首先,需要导入CSV库和Numpy库。然后,使用函数`reader()`读取CSV文件,并将数据转换为Numpy数组。以下是一个示例代码:
```python
import csv
import numpy as np
filename = 'test.csv' # 文件名
with open(filename, 'rt') as csvfile: # 打开文件
reader = csv.reader(csvfile, dialect='excel', delimiter=',') # 读取数据
x = list(reader) # 将每一行转换为列表
data = np.array(x, dtype='int') # 转换为numpy的数组,类型是int
print(data) # 打印数据
```
另外,还可以使用更简洁的代码来读取CSV文件,如下所示:
```python
import csv
with open("test.csv", "r") as csvfile:
reader = csv.reader(csvfile)
for line in reader:
print(line)
```
以上是两种常用的读取CSV文件的方法,你可以根据自己的需求选择适合的方法来读取CSV文件。\[1\]\[2\]
#### 引用[.reference_title]
- *1* *3* [Python读取csv文件的三种方式](https://blog.csdn.net/m0_37829442/article/details/100853879)[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^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [python如何读取csv数据](https://blog.csdn.net/m0_51713294/article/details/113032939)[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^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文