[英]Get folder name and file name with digits from file path Python
有没有办法获取包含数字的特定文件夹名称或文件名称? 我想检查是否有一个只有数字的文件夹名称。 如果有一个带有数字名称的文件夹,则返回数字。 如果没有,则检查文件名是否有数字并返回它们,否则返回默认文件名。 示例文件夹:
project
|_62951
|_test1.docx
|_68512
|_test2.docx
|_minor tasks
|_test3.docx
|_Plumbing project
|_69251
|_test4.dox
|_House address
|_69251 plumb.docx
|_test5.docx
期待结果:
project code: 62951
filename: test1.docx
project code: 68512
filename: test2.docx
project code: 68512
filename: test3.docx
project code: 69251
filename: test4.docx
project code: 69251
filename: 69251 plumb.docx
project code: test5.docx
filename: test5.docx
我浏览了 os 库并设法获取了文件路径和文件名,但它作为一个完整的文件路径出现,我不确定如何分解它。 请分享已解决问题的任何部分。 非常感谢: 当前代码:
#run through all folders
def get_files(source):
matches = []
for root, dirnames, filenames in os.walk(source):
for filename in filenames:
matches.append(os.path.join(root, filename))
return matches
def parse(files):
# run through all files
folders = []
for file in files:
filepath,filename = os.path.split(file)
filebreak = [filepath.split("\\")]
print('project code: %s' % filebreak)
print('file name: %s' % filename)
#check file name
path = 'C:\\Users\\quan.nguyen\\***\\***\\Project testing files\\XML'
parse(get_files(path))
结果:
file name: sample_book - Copy.xml
project code: [['C:', 'Users', 'quan.nguyen', '***', '***', 'Project testing files', 'XML', 'folder3']]
file name: sample_book.xml
project code: [['C:', 'Users', 'quan.nguyen', '***', '***', 'Project testing files', 'XML', 'folder3']]
file name: test - Copy.docx
project code: [['C:', 'Users', 'quan.nguyen', '***', '***', 'Project testing files', 'XML', 'folder3']]
file name: test - Copy.pdf
project code: [['C:', 'Users', 'quan.nguyen', '***', '***', 'Project testing files', 'XML', 'folder3']]
***是隐藏信息,是项目代码和名称
我只是获取完整的文件列表,然后过滤那些在文件名中包含数字的文件。 在这种情况下,要检查我从字符串模块加载digits
并检查设置的交集。
我不认为在这里使用os
模块是个好主意,代码的可读性因此变得更差, pathlib
对于大多数文件系统操作来说通常更好。
from pathlib import Path
from string import digits
BASE_FOL = '' # your base project folder
p = Path(BASE_FOL)
files = [f for f in p.rglob('*')
if f.is_file() and set(f.name).intersection(list(digits))]
for f in files:
print(f'Project: {f.parts[0]}\nFilename: {f.name}')
我没有任何类似的文件夹结构来测试,但它应该可以工作。
编辑:固定理解 - 忘记添加检查我们放置在列表中的所有对象都是实际文件,而不是文件夹。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.