我有以下代码:
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'
请帮助。
答案 0 :(得分:1)
您正在尝试从运行脚本的路径中打开文件。
您应该尝试打开完整路径
with open('/home/sainik/Final/' + file)
答案 1 :(得分:1)
您只传递open函数的文件名。您应该将路径传递给open函数。将文件路径传递给open函数的两种可能方法,相对路径或完整路径。
尝试:
with open( os.path.join('/home/sainik/Final/',str(folderno),file),'rb') as csvfile:
答案 2 :(得分: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