Do I need to pass the full path of a file in another directory to open()?

后端 未结 5 2130
盖世英雄少女心
盖世英雄少女心 2020-12-05 03:58

I have a folder with ten files in it which I want to loop through. When I print out the name of the file my code works fine:

import os
indir = \'/home/des/te         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 04:35

    If you are just looking for the files in a single directory (ie you are not trying to traverse a directory tree, which it doesn't look like), why not simply use os.listdir():

    import os  
    for fn in os.listdir('.'):
         if os.path.isfile(fn):
            print (fn)
    

    in place of os.walk(). You can specify a directory path as a parameter for os.listdir(). os.path.isfile() will determine if the given filename is for a file.

提交回复
热议问题