簡體   English   中英

如何在python中獲取文件夾名稱和文件名

[英]how to get a folder name and file name in python

我有一個名為myscript.py的python程序,它將在提供的路徑中提供文件和文件夾的列表。

import os
import sys

def get_files_in_directory(path):
    for root, dirs, files in os.walk(path):
        print(root)
        print(dirs)
        print(files)
path=sys.argv[1]
get_files_in_directory(path)

我提供的路徑是D:\\Python\\TEST並且其中包含一些文件夾和子文件夾,如下面提供的輸出所示:

C:\Python34>python myscript.py "D:\Python\Test"
D:\Python\Test
['D1', 'D2']
[]
D:\Python\Test\D1
['SD1', 'SD2', 'SD3']
[]
D:\Python\Test\D1\SD1
[]
['f1.bat', 'f2.bat', 'f3.bat']
D:\Python\Test\D1\SD2
[]
['f1.bat']
D:\Python\Test\D1\SD3
[]
['f1.bat', 'f2.bat']
D:\Python\Test\D2
['SD1', 'SD2']
[]
D:\Python\Test\D2\SD1
[]
['f1.bat', 'f2.bat']
D:\Python\Test\D2\SD2
[]
['f1.bat']

我需要這樣獲得輸出:

D1-SD1-f1.bat
D1-SD1-f2.bat
D1-SD1-f3.bat
D1-SD2-f1.bat
D1-SD3-f1.bat
D1-SD3-f2.bat
D2-SD1-f1.bat
D2-SD1-f2.bat
D2-SD2-f1.bat

我如何以這種方式獲得輸出。(請注意,這里的目錄結構只是一個示例。該程序應適用於任何路徑)。 我該怎么做呢。 是否為此有任何os命令。 你能幫我解決這個問題嗎? (其他信息:我正在使用Python3.4)

您可以嘗試使用glob模塊來代替:

import glob
glob.glob('D:\Python\Test\D1\*\*\*.bat')

或者,僅獲取文件名

import os
import glob
[os.path.basename(x) for x in glob.glob('D:\Python\Test\D1\*\*\*.bat')]

要獲得所需的內容,可以執行以下操作:

def get_files_in_directory(path):
    # Get the root dir (in your case: test)
    rootDir = path.split('\\')[-1]

    # Walk through all subfolder/files
    for root, subfolder, fileList in os.walk(path):
        for file in fileList:
            # Skip empty dirs
            if file != '':
                # Get the full path of the file
                fullPath = os.path.join(root,file)

                # Split the path and the file (May do this one and the step above in one go
                path, file = os.path.split(fullPath)

                # For each subfolder in the path (in REVERSE order)
                subfolders = []
                for subfolder in path.split('\\')[::-1]:

                    # As long as it isn't the root dir, append it to the subfolders list
                    if subfolder == rootDir:
                        break
                    subfolders.append(subfolder)

                # Print the list of subfolders (joined by '-')
                # + '-' + file
                print('{}-{}'.format( '-'.join(subfolders), file) )

path=sys.argv[1]
get_files_in_directory(path)

我的測試文件夾:

SD1-D1-f1.bat
SD1-D1-f2.bat
SD2-D1-f1.bat
SD3-D1-f1.bat
SD3-D1-f2.bat

這可能不是最好的方法,但是它將為您提供所需的東西。

暫無
暫無

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

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