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

searching for a filename with extension and printing its relative path

我有以下代码来打印文件名,该文件名是文件扩展名为 *.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

你需要使用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

filesdirs 列出 root 的 children。 dirs 因此列出了 file 的兄弟姐妹。你想打印这个:

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