在Python中打开csv文件时出错

时间:2017-08-17 05:47:42

标签: python csv import

我在(C:/Users/kgu/PycharmProjects/untitled1/test1.py)中保存了csv文件。命名为testdata.csv

我的代码是:

import csv
f=open('testdata.csv','r',encoding='utf-8')

错误信息在这里:

C:\Users\kgu\Anaconda3\python.exe 
C:/Users/kgu/PycharmProjects/untitled1/test1.py
Traceback (most recent call last):
File "C:/Users/kgu/PycharmProjects/untitled1/test1.py", line 3, in <module>
f=open('testdata.csv','r',encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: 'testdata.csv'

Process finished with exit code 1

我确实将testdata.csv保存在python项目文件夹中。 我不知道它有什么问题。

2 个答案:

答案 0 :(得分:0)

如果您使用Pandas,可以尝试:

import pandas as pd

filepath = "/yourfilepath/yourfile.csv"
# check your sep (";" , "," ...)
f = pd.read_csv(filepath, encoding="utf-8", sep="yoursep")

答案 1 :(得分:0)

你可以这样做 - 如果你在正确的工作目录中:

with open(testdata.csv', 'rb') as csvfile:
    data = [x for x in csv.reader(csvfile, delimiter='yourdelimiter')]