Reputation: 42329
Minimal working example that shows this error:
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)
I have a single file called 'data.dat' in that folder and python
returns the error:
----> 9 with open(myfile) as f:
....
IOError: [Errno 2] No existe el archivo o el directorio: u'data.dat'
Which translates to No file or directory: u'data.dat'.
Why is that u being added at the beginning of the file name and how do I get the code to correctly parse the file name?
Upvotes: 1
Views: 176
Reputation: 676
Your problem is that myfile
is just a filename, not the result of join(mypath,myfile)
.
Upvotes: 2
Reputation: 28268
The u
just indicates that it is a unicode string and is not relevant to the problem.
The file isn't found because you aren't adding the mypath
in front of the filename - try with open(join(mypath, myfile)) as f:
Upvotes: 6