Lin Ma Lin Ma - 3 months ago 12
Python Question

elegant way to check file directory path valid in Python 2.7

I am trying to read content of all files under a specific directory. I find it is a bit tricky if path name is not ends with

/
, then my code below will not work (will have I/O exception since
pathName+f
is not valid -- missing
/
in the middle). Here is a code example to show when it works and when it not works,

I can actually check if pathName ends with
/
by using endsWith, just wondering if more elegant solutions when concatenate path and file name for a full name?

My requirement is, I want to give input pathName more flexible to ends with both
\
and not ends with
\
.

Using Python 2.7.

from os import listdir
from os.path import isfile, join

#pathName = '/Users/foo/Downloads/test/' # working
pathName = '/Users/foo/Downloads/test' # not working, since not ends with/
onlyfiles = [f for f in listdir(pathName) if isfile(join(pathName, f))]
for f in onlyfiles:
with open(pathName+f, 'r') as content_file:
content = content_file.read()
print content

Answer

You would just use join again:

pathName = '/Users/foo/Downloads/test' # not working, since not ends with/
onlyfiles = [f for f in listdir(pathName) if isfile(join(pathName, f))]
for f in onlyfiles:
    with open(join(pathName, f), 'r') as content_file:
        content = content_file.read()
        print content

Or you could use glob and forget join:

from glob import glob

pathName = '/Users/foo/Downloads/test' # not working, since not ends with/

onlyfiles = (f for f in glob(join(pathName,"*")) if isfile(f))

for f in onlyfiles:
   with open(f, 'r') as content_file:

or combine it with filter for a more succinct solution:

onlyfiles = filter(isfile, glob(join(pathName,"*")))
Comments