簡體   English   中英

搜索帶有擴展名的文件名並打印其相對路徑

[英]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的子代。 因此, dirs列出了file兄弟姐妹。 您想打印此:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM