[英]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
files
和dirs
列出了root
的子代。 因此, dirs
列出了file
兄弟姐妹。 您想打印此:
print(os.path.relpath(os.path.join(root, file)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.