从 directory/subdirectory in Python 生成只有文件名的字符串,没有目录地址

Generate string of only file names from directory/subdirectory in Python, no directory address

注意:请参阅底部重新使用 pathlib 的问题的编辑版本

我想遍历 directory/subdirectories (Mac) 并将所有文件名列为字符串。我可以做到这一点,但字符串包含目录信息,例如 /Users/TK/Downloads/Temp/a_c/imgs_a/a1.tif

我只想要“a1.tif”。

这是我的代码


'''
    For the given path, get the List of all files in the directory tree
'''

import os
def getListOfFiles(dirName):
    # create a list of file and sub directories
    # names in the given directory
    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)

    return allFiles

dirName = "/Users/TK/Downloads/Temp_Folder/a_c";
# Get the list of all files in directory tree at given path
listOfFiles = getListOfFiles(dirName)
file_string = str(sorted(listOfFiles))
print(file_string) 

如何去掉目录信息而只列出文件名(没有扩展名更好)

--根据以下建议更改代码-- --它可以解决一些小问题--

from pathlib import Path

path = os.chdir("/Users/TK/Downloads/Temp_Folder/a_c")

path = Path.cwd()

files = []
for file in path.rglob('*'):  # loop recursively over all subdirectories
    files.append(file.name)

files = [file.stem for file in path.rglob('*')]

fileList = str(sorted(files))
print(fileList)

结果为['.DS_Store', '.DS_Store', '.tif', 'a1', 'a2', 'a3', 'a4'、'a5'、'a6'、'b1'、'b2'、'b3'、'b4'、'b5'、'b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'imgs_a', 'imgs_b', 'imgs_c']

几乎完美 - 除了 'a1', 'a2'...'c6'

我能去掉所有东西吗

我也无法将目录放入 path = Path.cwd() 这就是我使用 path = os.chdir("/Users/TK/Downloads/Temp_Folder/a_c")

的原因

------------编辑问题------------

我喜欢按照下面的建议使用 pathlib 的想法。根据我在网上的研究,它似乎是完成工作的最简单代码版本,它应该可以工作吗?但不知何故,它并没有给我我想要的东西。

我试过的路径库代码

from pathlib import Path
path = Path('/Users/TK/Downloads/Temp_Folder/a_c')
files = [file.stem for file in path.rglob('*')]
print(files)
from pathlib import Path
print(Path('/Users/TalaKaplinovsky/Downloads/Patrick_Strips_Temp_Folder/a_c')stem)

都给我这个 两个版本的输出相同: '/Users/TK/Downloads/Temp_Folder/a_c/.DS_Store', '/Users/TK/Downloads/Temp_Folder/a_c/imgs_b/b2.tif' '/Users/TK/Downloads/Temp_Folder/a_c/imgs_b/b3.tif', '/Users/TK/Downloads/Temp_Folder/a_c/imgs_b/b1.tif', '/Users/TK/Downloads/Temp_Folder/a_c/imgs_a/.tif', '/Users/TK/Downloads/Temp_Folder/a_c/imgs_a/a4.tif',

我只想要 'b2'、'b3'、'b1'、'a4' 并按顺序排序(a4、b1 等)

您可以使用 pathlib(与 python 捆绑在一起)来相当简单地完成此操作:

from pathlib import Path

path = Path.cwd()  # insert your path 

files = []
for file in path.rglob('*'):  # loop recursively over all subdirectories
    files.append(file.name)

或者,更简单:

files = [file.name for file in path.rglob('*')]

要删除扩展,您可以使用 Path.stem:

files = [file.stem for file in path.rglob('*')]
import os
path = '/home/User/Documents/file.txt'
basename = os.path.basename(path)

# Print the basename name 
print(basename)

filename = basename.split(".")[0]
print(filename)

来自这篇文章:https://www.geeksforgeeks.org/python-os-path-basename-method/

已编辑以下建议

fileList = ['.DS_Store', '.DS_Store', '.tif', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'b1', 'b2', 'b3', 'b4', 'b5', '    b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'imgs_a', 'imgs_b', 'imgs_c']

new_result = [c for c in fileList if len(c)<3]
print(new_result)

好吧 - 愚蠢的我 - pathlib 确实有效,我 运行 错了 window。 此代码有效!!

读取目录和子目录中的文件名,以排序格式打印出仅文件名列表(无目录列表)。

from pathlib import Path
path = Path('/Users/TK/Downloads/Temp_Folder/a_c')
files = [file.stem for file in path.rglob('*')]
print(sorted(files))

输出: ['.DS_Store', '.DS_Store', '.tif', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'imgs_a', 'imgs_b', 'imgs_c']

注意 - 这也是 returns 目录 'imgs_a' 等中的文件夹; 和隐藏文件'.DS_Store'; 还有一个叫做“.tif”的东西,它不是一个实际的文件

为了只获取 'a1'、'a2' 等(都是 .tif 文件),我这样做了:

from pathlib import Path
path = Path('/Users/TK/Downloads/Temp_Folder/a_c')
files = [file.stem for file in path.rglob('*.tif')] #select only '.tif' files
files.remove(".tif") #remove the unwanted '.tif' file
print(sorted(files)) 

输出: ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6']

我不需要的一切现在都消失了,只列出了实际的 tif 文件,没有扩展名