[英]Cannot run csv module on Python 3.7/Spyder/Anaconda
I'm trying to open a CSV file on Python 3.7/Spyder/Anaconda IDE.我正在尝试在 Python 3.7/Spyder/Anaconda IDE 上打开一个 CSV 文件。
I want to learn how to import csv files either by using pandas and by using the csv libraries.我想学习如何通过使用熊猫和使用 csv 库来导入 csv 文件。
The following code worked well and a csvfile variable containing the data frame was created:以下代码运行良好,并创建了一个包含数据框的csvfile变量:
import pandas as pd
csvfile = pd.read_csv(r'C:\Users\Documents\PyLearning\data_file.csv', sep=',')
However I didn't get the same result with the csv module.但是我没有得到与 csv 模块相同的结果。 After running the following code, nothing happend.运行以下代码后,什么也没发生。
import csv
csvfile = open('data_file.csv', 'rb')
reader = csv.reader(csvfile)
I got no error message but no variable was created.我没有收到错误消息,但没有创建变量。
I would like to some help to understand why this is happening.我想帮助理解为什么会发生这种情况。
EDIT: It seems csv module was replaced by unicodecsv module at more recent python versions https://pypi.org/project/unicodecsv/编辑:似乎 csv 模块在更新的 python 版本https://pypi.org/project/unicodecsv/ 中被 unicodecsv 模块取代
If you're looking for how to use a builtin Python module (the csv
module, for example), I would recommend looking at the official Python documentation.如果您正在寻找如何使用内置 Python 模块(例如csv
模块),我建议您查看官方 Python 文档。
You can find the documentation for the csv module here .您可以在此处找到 csv 模块的文档。
Here's the first example they give of reading a csv file (see https://docs.python.org/3/library/csv.html#examples ):这是他们提供的第一个读取 csv 文件的示例(请参阅https://docs.python.org/3/library/csv.html#examples ):
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
In the loop, you can access row
to store it in whatever data structure you prefer.在循环中,您可以访问row
以将其存储在您喜欢的任何数据结构中。
For example, to put it in all in a list:例如,要将其全部放入列表中:
with open('some.csv', newline='') as f:
reader = csv.reader(f)
data = [row for row in reader]
print(data)
The beauty of using pandas' read_csv is that it automatically and most importantly quickly converts said csv into a usable dataframe.使用 Pandas 的 read_csv 的好处在于它可以自动且最重要的是快速将所述 csv 转换为可用的数据帧。
using csv.reader simply refers to the csv in question but you would have to call an iterator to get a result.使用 csv.reader 只是指有问题的 csv,但您必须调用迭代器才能获得结果。
ie: (from https://docs.python.org/3/library/csv.html )即:(来自https://docs.python.org/3/library/csv.html )
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.