簡體   English   中英

提取完整路徑和文件名

[英]Extract full Path and File Name

嘗試編寫一個 function 遍歷文件系統並返回絕對路徑和文件名以用於另一個 function。

示例"/testdir/folderA/222/filename.ext"

嘗試了多個版本后,我似乎無法使其正常工作。

filesCheck=[]

def findFiles(filepath):
    files=[]
    for root, dirs, files in os.walk(filepath):
        for file in files:
            currentFile = os.path.realpath(file)
            print (currentFile)
            if os.path.exists(currentFile):
                files.append(currentFile)

    return files

filesCheck = findFiles(/testdir)

這將返回"filename.ext" (只有一個)。

currentFile = os.path.join(root, file)替換os.path.realpath(file)並進入第一個目錄中的循環。 嘗試os.path.join(dir, file)並失敗,因為我的文件夾之一被命名為222

我繞着圈子轉了一圈,離得有點近,但沒能讓它工作。 在 Linux 上運行 Python 3.6

您的代碼有幾處問題。

  1. 有多個值被分配給變量名files
  2. 您不會將root目錄添加到os.walk()返回的每個文件名中,這可以使用os.path.join()來完成。
  3. 您沒有將字符串傳遞給findFiles() function。

如果您解決了這些問題,則不再需要調用os.path.exists()因為您可以確定它確實如此。

這是一個工作版本:

import os

def findFiles(filepath):
    found = []
    for root, dirs, files in os.walk(filepath):
        for file in files:
            currentFile = os.path.realpath(os.path.join(root, file))
            found.append(currentFile)

    return found

filesCheck = findFiles('/testdir')
print(filesCheck)

嗨,我認為這是您需要的。 也許你可以試一試:)

from os import walk

path = "C:/Users/SK/Desktop/New folder"

files = []
for (directoryPath, directoryNames, allFiles) in walk(path):
    for file in allFiles:
        files.append([file, f"{directoryPath}/{file}"])

print(files)

Output:

[ ['index.html', 'C:/Users/SK/Desktop/New folder/index.html'], ['test.py', 'C:/Users/SK/Desktop/New folder/test.py'] ]

暫無
暫無

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

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