【问题标题】:searching for a filename with extension and printing its relative path搜索带有扩展名的文件名并打印其相对路径
【发布时间】:2015-04-06 09:54:21
【问题描述】:

我有下面的代码来打印文件名,它是文件扩展名 *.org 的查找条件。我如何打印找到的文件的相对路径。提前致谢

def get_filelist() : 

directory = "\\\\networkpath\\123\\abc\\"
filelist = []
for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('Org'):
            print(str(dirs) +"\\" + str(file)) #prints empty list [] followed by filename
            filelist.append(os.path.splitext(file)[0])

return (filelist)

请把我看成python新手

【问题讨论】:

    标签: python dir os.walk


    【解决方案1】:

    files 和 dirs 列出 root 的子级。 dirs 因此列出了file 的兄弟姐妹。你想打印这个:

    print(os.path.relpath(os.path.join(root, file)))
    

    【讨论】:

    • 谢谢..但你能告诉我如何获取文件的相对路径
    • 您可以使用os.path.relpath 查找当前工作目录的相对路径。 docs.python.org/3.4/library/…
    【解决方案2】:

    你需要使用os.path.join:

    def get_filelist() : 
    
        directory = "\\\\networkpath\\123\\abc\\"
        filelist = []
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith('org'): # here 'org' will be in small letter
                    print(os.path.join(root,file))
                    filelist.append(os.path.join(root,file))
    
        return filelist
    

    【讨论】:

    • Dirs 是一个列表,而不是目录
    • 输入错误,这里应该是root
    • @Hackaholic : 对文件的相对路径有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多