2

I need to process the filenames from a directory by creating the list of the filenames. But my resulting list contains entries for symbolic links too. How can I get pure filenames in a particular directory using python.

I have tried:os.walk,os.listdir,os.path.isfile

But all are including symbolic links of type 'filename~' to the list :(

The glob.glob adds the path to the list which I don't need.

I need to use it in a code like this:

files=os.listdir(folder)    
for f in files:
     dosomething(like find similar file f in other folder)

Any help? Or please redirect me to the right answer. Thanks

Edit: the tilde sign is at end

Kaur
  • 279
  • 1
  • 6
  • 18

2 Answers2

1

You can use os.path.islink(yourfile) to check if yourfile is symlinked, and exclude it.

Something like this works for me:

folder = 'absolute_path_of_yourfolder' # without ending /
res = []
for f in os.listdir(folder):
    absolute_f = os.path.join(folder, f)
    if not os.path.islink(absolute_f) and not os.path.isdir(absolute_f):
        res.append(f)

res # will get you the files not symlinked nor directory
...
Anzel
  • 19,825
  • 5
  • 51
  • 52
  • I tried files = [f for f in os.listdir(folder) if not os.path.islink(os.path.join(folder,f))] But the list of files still contain symbolic links :( – Kaur Oct 27 '14 at 12:13
  • @Kaur, I've included a sample which works on my laptop – Anzel Oct 27 '14 at 12:27
1

To get regular files in a directory:

import os
from stat import S_ISREG

for filename in os.listdir(folder):
    path = os.path.join(folder, filename)
    try:
        st = os.lstat(path) # get info about the file (don't follow symlinks)
    except EnvironmentError:
        continue # file vanished or permission error
    else:
        if S_ISREG(st.st_mode): # is regular file?
           do_something(filename)

If you still see 'filename~' filenames then it means that they are not actually symlinks. Just filter them using their names:

filenames = [f for f in os.listdir(folder) if not f.endswith('~')]

Or using fnmatch:

import fnmatch

filenames = fnmatch.filter(os.listdir(folder), '*[!~]')
jfs
  • 399,953
  • 195
  • 994
  • 1,670