2017-09-18 230 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: