音乐小工具

删除重复文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
import hashlib


def get_file_hash(file_path):
    """
    计算文件的哈希值
    """
    with open(file_path, 'rb') as f:
        file_hash = hashlib.md5()
        while True:
            data = f.read(8192)
            if not data:
                break
            file_hash.update(data)
    return file_hash.hexdigest()


def find_duplicate_files(folder_path):
    """
    查找重复的文件
    """
    file_hashes = {}  # 保存每个文件的哈希值
    duplicate_files = []  # 保存重复的文件

    # 遍历文件夹中的所有文件
    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            file_hash = get_file_hash(file_path)  # 计算文件的哈希值

            if file_hash in file_hashes:  # 如果已经有相同哈希值的文件
                duplicate_files.append((file_path, file_hashes[file_hash]))  # 保存重复的文件
            else:
                file_hashes[file_hash] = file_path  # 记录文件的哈希值

    return duplicate_files


def delFile(file_path):
    try:
        os.remove(file_path)
        print('文件删除成功: ', file_path)
    except Exception as e:
        print('文件删除失败:', e)


folder_path = '我的歌单'  # 文件夹路径
duplicate_files = find_duplicate_files(folder_path)  # 查找重复的文件

for file1, file2 in duplicate_files:
    print("重复文件:%s%s" % (file1, file2))
    delFile(file2)

通过文件名来实现两个文件夹间的文件同步:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import os
import shutil

# 说明:通过文件名来实现文件同步

# 定义两个文件夹路径
file1_path = r'E:\BaiduSyncdisk\我的歌单'    # 同步文件夹
file2_path = r'F:'    # 被同步的文件夹

# 获取两个文件夹中所有文件的文件名
files_in_file1 = set(os.listdir(file1_path))
files_in_file2 = set(os.listdir(file2_path))

# 查找需要删除的文件和需要添加的文件
to_delete = files_in_file2 - files_in_file1
to_add = files_in_file1 - files_in_file2

# 删除需要删除的文件
for file_name in to_delete:
    try:
        os.remove(os.path.join(file2_path, file_name))
        print('已删除文件:', file_name)
    except:
        print('已跳过文件:', file_name)

# 复制需要添加的文件
for file_name in to_add:
    src_file_path = os.path.join(file1_path, file_name)
    dst_file_path = os.path.join(file2_path, file_name)
    shutil.copy(src_file_path, dst_file_path)
    print('已添加文件:', file_name)
0%