2014-10-27 47 views
0

我需要通过创建文件名列表来处理目录中的文件名。 但是我的结果列表也包含符号链接的条目。我如何使用python在特定目录中获得纯文件名。如何获取特定目录中的文件列表,忽略使用python的符号链接?

我曾尝试:os.walk,os.listdir,os.path.isfile

但这一切都包括'filename~'类型的列表:(

glob.glob增加了,我不需要路径列表符号链接

。我需要在这样的代码中使用它:

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

任何帮助?或请将我重定向到正确t答案。由于

编辑:波浪符号是在结束

+1

过滤器基于'不file.startswith( '〜')' – 2014-10-27 11:59:52

+0

如果您需要支持OS X的别名,看这里:http://stackoverflow.com/a/21245832/2829764 – kuzzooroo 2014-10-27 12:08:35

+0

@kuzzooroo使用Linux – Kaur 2014-10-27 12:10:52

回答

0

您可以使用os.path.islink(yourfile)检查yourfile被链接,并排除它。

像这样的事情对我的作品:

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 
... 
+0

,f))] \t 但是文件列表中仍然包含符号链接:( – Kaur 2014-10-27 12:13:56

+0

好吧,你在linux上对吗?让我仔细检查 – Anzel 2014-10-27 12:14:23

+0

@Kaur,我已经包含了一个示例,它适用于我的笔记本电脑 – Anzel 2014-10-27 12:27:29

1

要在目录中获取的常规文件:

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) 

如果仍然看到'filename~'文件名,那么就意味着他们实际上不是符号链接。

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

或者用fnmatch:只是用自己的名字进行筛选

import fnmatch 

filenames = fnmatch.filter(os.listdir(folder), '*[!~]') 
+0

谢谢。我尝试了'fnmatch'这个你以前的建议。似乎没有工作。 – Kaur 2014-10-27 12:29:41

+0

@Kaur:这就是我删除它的原因。我已经添加了'fnmatch'解决方案。 – jfs 2014-10-27 12:32:55

+0

是这个'fnmatch'正在工作。早些时候是'*〜'。非常感谢! – Kaur 2014-10-27 12:35:01

相关问题