2017-09-18 203 views
1

阅读CSV文件时,我有以下代码:IO错误蟒蛇

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   
运行代码时

,我收到以下错误:

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' 

请帮助。

回答

1

您正尝试从正在运行该脚本的路径中打开该文件。

你应该尝试打开的完整路径

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

你的脚本看着它自己的目录文件4.csv。 请尝试像这样:

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 
1

您只传递打开函数的文件名。您应该将路径传递给打开的函数。传递文件路径以打开函数的两种可能方式,相对路径或完整路径。

尝试:

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