1

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?

1
  • thats just in the representation ... it means it is a unicode string ... the u is not actually in the string and certainly is not your problem Commented Jun 5, 2013 at 17:57

2 Answers 2

6

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, but how do I fix that?
2

Your problem is that myfile is just a filename, not the result of join(mypath,myfile).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.