简体   繁体   English

在python中读取csv文件时出现IO错误

[英]IO error when reading csv files in python

I have the following code: 我有以下代码:

for file in os.listdir('/home/sainik/Final/'+str(folderno)):
        if file.endswith('.csv'):
            print file
            with open(file,'rb') as csvfile:
                spamreader = csv.reader(csvfile)
                for row in spamreader:
                    print row        

when running the code, I am getting the following error: 运行代码时,出现以下错误:

Traceback (most recent call last):
  File "/home/sainik/Final/Programs/sainik.py", line 28, in <module>
    with open(file,'rb') as csvfile:
IOError: [Errno 2] No such file or directory: '4.csv'

Kindly help. 请帮助。

You are trying to open the file from the path you are running the script. 您正在尝试从运行脚本的路径打开文件。

You should try to open the full path 您应该尝试打开完整路径

with open('/home/sainik/Final/' + file)

You are passing only the filename for open function. 您仅传递用于打开功能的文件名。 You should pass path to the open function. 您应该将路径传递给open函数。 Two possible ways to pass the path of file to open function, either relative path or full path. 将文件的路径传递给打开功能的两种可能方法是相对路径或完整路径。

try: 尝试:

with open( os.path.join('/home/sainik/Final/',str(folderno),file),'rb') as csvfile:

Your script is looking at it's own directory for file 4.csv . 您的脚本正在查找文件4.csv的自身目录。 Try it like this: 像这样尝试:

for file in os.listdir('/home/sainik/Final/'+str(folderno)):
        if file.endswith('.csv'):
            print file
            with open(/home/sainik/Final/'+str(folderno)+'\/'+file,'rb') as csvfile:
                spamreader = csv.reader(csvfile)
                for row in spamreader:
                    print row  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM