【问题标题】:Generate string of only file names from directory/subdirectory in Python, no directory address在 Python 中从目录/子目录生成仅文件名的字符串,没有目录地址
【发布时间】:2022-01-17 09:32:18
【问题描述】:

注意:使用 pathlib 在底部查看问题的编辑版本

我想遍历目录/子目录 (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 的想法。从我在网上的研究来看,它似乎是完成工作的最简单的代码版本,它应该可以工作吗?但不知何故,它并没有给我我想要的东西。

我试过的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 等)

【问题讨论】:

  • “摆脱除 a1 - c6 之外的所有内容”是什么意思?定义合法文件的模式是什么?只是一个字母后跟一个数字?
  • 是的,这些文件被命名为“a1.tif、a2.tif 等”。但我解决了。请看下面我的回答。感谢您的帮助

标签: python list file directory pathlib


【解决方案1】:

您可以通过使用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('*')]

【讨论】:

  • 我喜欢 pathlib 的想法,但不知何故它并没有给我想要的东西。尝试了两种代码,但始终得到相同的结果:请参阅上面的编辑问题
  • 这很奇怪,因为对我来说它按预期工作......你使用的是什么 python 版本?哦,Path.cwd() 只是一个示例,您应该插入自己的路径
  • 非常感谢,是的,我正在做一些愚蠢的事情——它有效,请参阅下面的答案。感谢您的帮助
【解决方案2】:
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)

【讨论】:

  • 这只会生成子文件夹的名称 (?)。输出是 [a_c a_c]。应该在我上面编辑的问题中列出...
  • 是的,因为你已经编辑了这是我的建议,有很多方法可以做到这一点,但如果文件名不是每次都改变,你可以使用上面编辑的代码。跨度>
【解决方案3】:

好的 - 我很傻 - pathlib 确实有效,我运行了错误的窗口。 此代码正在运行!

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

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']

注意 - 这也会返回目录“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 文件,没有扩展名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 2011-10-14
    • 2012-02-29
    • 1970-01-01
    • 2018-05-05
    • 2023-03-15
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多