简体   繁体   English

搜索带有扩展名的文件名并打印其相对路径

[英]searching for a filename with extension and printing its relative path

I have the below code to print the filename which is find criteria with file extension *.org. 我有以下代码来打印文件名,这是文件扩展名为* .org的查找条件。 How could I print the relative path of the file found. 我如何打印找到的文件的相对路径。 Thanks in advance 提前致谢

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)

Please see me as novice in python 请在python中将我视为新手

you need to use os.path.join : 您需要使用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

files and dirs list the children of root . filesdirs列出了root的子代。 dirs thus lists siblings of file . 因此, dirs列出了file兄弟姐妹。 You want to print this instead: 您想打印此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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