Python读取csv-fi

2024-04-25 00:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很陌生。。。。你知道吗

关于将csv文件读入列表,Stackoverflow有很多答案,我使用了一个答案来获得以下内容:

#opens the csv file and reads in the data
filepath = 'Online Retail.csv'
spent = 0
with open(filepath) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

然后我可以循环使用readCSV变量并得到一些结果…太好了。我遇到的问题是,通过代码我想再次访问readCSV列表,但它已关闭,我得到错误:

I/O operation on closed file.

如果需要,如何再次引用readCSV变量。或者有没有更好的方法来导入数据,这样它只发生一次,然后我就可以在脚本的任何时候提取我想要的任何数据?你知道吗

我正在使用visualstudio代码。你知道吗


Tags: and文件csvthe数据csvfile答案代码
2条回答

这样,您只能访问with中的csv文件。文件在with块的末尾关闭。你知道吗

with open(filepath) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    # you can access the file here

# you cannot access the file here

如果您需要它来进一步访问文件,您可以将它保存在listdict中,或者如果它包含大量数据,请用pandas打开它

import pandas as pd

file = pd.read_csv(filepath)

您需要定义模式(读、写或附加),因此,在这里,当您读取文件时,您需要读模式,其写入方式如下with open

with open(filepath, "r") as csvfile:

如果csvfile是一个文件对象,那么在有区别的平台上,必须使用“b”标志打开它。你知道吗

with open(filepath, "rb") as csvfile:

相关问题 更多 >