简体   繁体   中英

check if it's File

I have written very small code to check if it's file. I was expecting I should get "yes" print but I did not get. Am I doing any silly mistake.

os.listdir(os.getcwd()+"/../py")
a = ['a.py', 'a.pyc']
>>> for _a in a:
...  if os.path.isfile(_a):
...     print "yes"

You need to provide a full path ; you are only providing a relative path, so Python looks in the current working directory for these and there is no file named a.py in os.getcwd() .

Start by storing the path to the other directory in a variable:

path = os.path.abspath('../py')
for name in os.listdir(path):
    if os.path.isfile(os.path.join(path, name):
        print "yes", name, "is a file!"

I used os.path.abspath() instead of os.getcwd() to turn your relative path into a normalized absolute path, and used os.path.join() to then use that path to construct absolute paths for the list of names that os.listdir() returned.

a.py looks for the file named a.py in the current directory . Your code seems to imply that you should be supplying a path ( ../py ?)

For example:

>>> for _a in a:
...  if os.path.isfile(os.path.join('../py', _a)):
...     print "yes"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM