【发布时间】: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