6

I have the following code which checks if the directory exists

def download(id, name, bar):
    cwd = os.getcwd()
    dir = os.path.join(cwd,bar)
    partial = os.path.join(cwd, id + ".partial")
    print os.path.isdir(dir)
    if(os.path.isdir(dir)):
        print "dir exists"
        dir_match_file(dir, bar)
    else:
        print dir

For a directory that actually exists, it returns "False". Here is the output:

False
/scratch/rists/djiao/Pancancer/RNA-seq/CESC/TCGA-BI-A0VS-01A-11R-A10U-07

When I go to python interactive session and type in os.path.isdir("/scratch/rists/djiao/Pancancer/RNA-seq/CESC/TCGA-BI-A0VS-01A-11R-A10U-07"), it returns "true".

Why does it say false when the folder exists?

ddd
  • 4,665
  • 14
  • 69
  • 125
  • 2
    Are you running the code as the same user in both instances? – unutbu Jul 25 '14 at 21:43
  • 2
    Change `print dir` to `print(repr(dir))`. Let's see if there is some "invisible" character there such as a CR/LF at the end. – unutbu Jul 26 '14 at 01:54
  • @unutbu ah, there is a '\n' at the end. I read in bar from a file with readlines. Guess I have to rstrip it. What exactly does repr do on a string? – ddd Jul 26 '14 at 04:15
  • `repr(obj)` returns a `str` which is intended to be an *unambiguous* representation of the object. It's useful to inspect `basestrings` (`str`s or `unicode`) using `repr` since it will tell you exactly what bytes or code points the `basestring` is composed of. – unutbu Jul 26 '14 at 12:06
  • You should be aware that `dir` is a built-in function. Better to pick a different variable name – chaimp Mar 17 '15 at 17:15

1 Answers1

12

The dir in download had whitespace at the end while the dir defined in the interactive session did not. The difference was discovered by printing repr(dir).

In [3]: os.path.isdir('/tmp')
Out[3]: True

In [4]: os.path.isdir('/tmp\n')
Out[4]: False
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677