显示此错误的最小工作示例:
from os import listdir, getcwd
from os.path import isfile, join, realpath, dirname
import csv
def gd(mypath, myfile):
# Obtain the number of columns in the data file
with open(myfile) as f:
reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
for i in range(20):
row_20 = next(reader)
# Save number of clumns in 'num_cols'.
num_cols = len(row_20)
return num_cols
mypath = realpath(join(getcwd(), dirname(__file__)))
# Iterate through all files. Stores name of file in 'myfile'.
for myfile in listdir(mypath):
if isfile(join(mypath,myfile)) and (myfile.endswith('.dat')):
num_cols = gd(mypath, myfile)
print(num_cols)
我在该文件夹中有一个名为“data.dat”的文件并python
返回错误:
----> 9 with open(myfile) as f:
....
IOError: [Errno 2] No existe el archivo o el directorio: u'data.dat'
转换为No file or directory: u'data.dat'。
为什么将u添加到文件名的开头以及如何让代码正确解析文件名?