python - 有没有办法根据两者中的匹配字符串将文件放入文件夹中?
问题描述
我对 python 很陌生,我用它作为我的第二次体验来继续我的学习。我的第一个项目(使用 pandas 进行数据分析)会比这个更难,但这将是一个新的领域,我需要一些帮助才能开始,因为我什至不知道在任何文档中搜索什么。
我在一个目录中有许多以电视节目命名的文件夹。我在另一个目录中有很多文件,多个剧集,其中几个节目。一个问题是,当我下载每一集时,它都存储在同一个标题的文件夹中。到目前为止,我一直在手动组织文件,但它已经到了自动化它会很好的地方(也是一个很好的学习练习)。有没有办法在“下载”文件夹中搜索包含包含字符串的文件的文件夹,比如“家园”,并将该文件(剧集)移动到另一个目录中标题为“家园”的文件夹中?我还需要为每个文件/文件夹匹配多个字符串,例如“Game”和“Thrones”。将它们移动到目录很容易,但是获得匹配的字符串是我想要了解的地方。
folders = 'list of folders in downloads'
#maybe I need to create a list here or a function that creates a list?
source_dir = "C:\Users\Downloads"
destination_dir = "C:\Users\TV Shows"
for folder_names in folders:
if folder_name contains destination_name:
# destination_name will be undefined but this is what i want
source_path = str(source_dir) + str(file_name) + str(.mp4)
destination_path = str(destination_dir) + str(file_name) +
str(.mp4)
shutil.move(source_path, destination_path)
if not:
do nothing
必须更改它,因为有些变量会产生错误并且语法不好,但这是我想要的一般想法。
解决方案
如果您有很多文件和文件夹,请使用for
-loops 来处理它们。
您必须将文件名拆分为单词 - split(' ')
- 并使用for
-loop 分别检查文件夹名称中的每个单词,并计算文件夹名称中的单词。当计数为 2 或更多时,移动文件。
或多或少:
all_filenames = [
'Game of Throne part II.mp4',
'other file.mp4',
]
all_folders = [
'Game Throne',
'Other Files'
]
for filename in all_filenames:
words = filename.lower().split(' ')
moved = False
for folder in all_folders:
count = 0
for word in words:
if word in folder.lower():
count += 1
if count >= 2:
print('count:', count, '|', filename, '->', folder)
# TODO: move file
moved = True
break
if not moved:
print('not found folder for:', filename)
# TODO: you could move file to `Other Files`
编辑:获取所有匹配文件夹并要求用户选择正确文件夹的版本。
我没有测试它。可能需要更多代码来检查用户是否选择了正确的号码。并最终添加选项以跳过它而不移动文件。
all_filenames = [
'Game of Throne part II.mp4',
'other file.mp4',
]
all_folders = [
'Game Throne',
'Other Files'
]
for filename in all_filenames:
words = filename.lower().split(' ')
matching = []
for folder in all_folders:
count = 0
for word in words:
if word in folder.lower():
count += 1
if count >= 2:
print('count:', count, '|', filename, '->', folder)
matching.append(folder)
#if not matching:
if len(matching) == 0:
print('not found folder for:', filename)
# TODO: you could move file to `Other Files`
elif len(matching) == 1:
print('move:', filename, '->', matching[0])
# TODO: move file to folder matching[0]
else:
for number, item in enumerate(matching):
print(number, item)
answer = int(input('choose number:'))
print('move:', filename, '->', matching[answer])
# TODO: move file to folder matching[answer]
推荐阅读
- ios - 分析来自 Test Flight - React Native App 的崩溃报告
- node.js - 使用 NodeJS Express 服务器从 MongoDb 中的 ObjectId 以外的字段中获取数据
- java - 注册。在 Linux 上使用 Overlay 在 PDF 上添加水印不起作用,但在 Windows 上
- sql - ORACLE SQL 喜欢或条件
- python - 在 python 中解析网站
- android - 如何获取用户在 TimePicker 和 DatePicker 中选择的时间和日期?
- sql - 在不使用 TOP 的情况下为 SSMS 选择 Last Row Hackerrank 挑战者
- r - 更改列数不确定的数据帧的格式(添加“.”表示 1000 位数字)
- flutter - 如何在颤动中将小部件(如芯片或容器)添加到文本字段
- amazon-web-services - AWS 服务:ecs-tasks.amazonaws.com 条件键不起作用