如何将文件排序到类似的目录结构中?

2024-06-16 14:06:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的不太确定如何在不让人觉得不识字的情况下把这些文件放在一个python程序中,将它们转换成torrent文件,然后根据之前转换的文件在不同的目录中进行排序。我有一些代码,它能够成功地转换所有文件,但我不知道如何实现排序部分。任何帮助都将不胜感激。在

import os
import sys
import shutil

for (dir, _, files) in os.walk("C:\Torrents"):
    for f in files:
        path = os.path.join(dir, f)
        print(path)
        os.system('python py3createtorrent.py "' + path + '"
                  "udp://tracker.openbittorrent.com:80/announce"')

shutil.rmtree('__pycache__')

以下是目录结构的示例:

screenshot showing directory structure in windows explorer


Tags: 文件pathinimport程序目录for排序
1条回答
网友
1楼 · 发布于 2024-06-16 14:06:49

如果您只想处理lexicographical order中源目录中的文件,那么可以通过在迭代之前显式地排序它们所在的列表来轻松完成,如下所示:

import os
import sys
import shutil

for (dir, _, files) in os.walk("C:\\Torrents"):  # note double backslashes
    for f in sorted(files):  # note call to sorted() function
        path = os.path.join(dir, f)
        print(path)
        os.system('python py3createtorrent.py "' +
                  path +
                  '" "udp://tracker.openbittorrent.com:80/announce"')

shutil.rmtree('__pycache__')

如果py3createtorrent.py脚本向来自同一源子目录的所有文件名添加相同的文件夹前缀'DAW_'或{},则它们在目标文件夹中的相对顺序将保持相同。在

相关问题 更多 >