我想遍歷目錄/子目錄(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")
uj5u.com熱心網友回復:
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('*')]
uj5u.com熱心網友回復:
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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414153.html
標籤:
上一篇:Java檔案洗掉
