代码之家  ›  专栏  ›  技术社区  ›  Colin

缩短嵌套文件夹名称

  •  0
  • Colin  · 技术社区  · 11 月前

    我们正在使用在线文件存储库(类似于SharePoint,但不是Microsoft)。问题是它允许创建长路径。我们正在将嵌套文件夹下载为zip文件,然后在计算机上本地提取它们,但当我们尝试将解压缩的路径上传到SharePoint时,它达到了路径长度限制。 巢很长,大约有8到10个子文件夹。

    为了解决这个问题,我试图编写一个脚本,将每个文件夹缩短到前8个字符。我尝试了PowerShell,但它达到了相同的路径长度限制,无法运行。 我在Python中尝试了这一点,我有一个循环来遍历文件夹,但一旦它重命名了第一个超过8个字符的文件夹,它就会退出循环,不再继续重命名其余的文件夹。

    我希望这个问题对其他人来说可能是显而易见的。

    以下是代码:

    def shorten_folder_names(root_folder, max_length):
        # Create a text file to store the old and new folder names
        with open("folder_names.csv", "w") as file:
            # Walk through all folders and subfolders
            for dirpath, dirnames, filenames in os.walk(root_folder):
                for dirname in dirnames:
                    old_name = os.path.join(dirpath, dirname)
                    # Skip folders that are already shorter than the specified length
                    if len(dirname) <= max_length:
                        continue
                    new_name = os.path.join(dirpath, dirname[:max_length])
                    # Rename the folder to the new name (shortened to the specified length)
                    os.rename(old_name, new_name)
                    # Write the old and new folder names to the text file
                    file.write(f"{old_name} -> {new_name}\n")
    
    
    1 回复  |  直到 11 月前
        1
  •  0
  •   Dylan P.    11 月前

    正如你已经提到的,你的问题目前在于你的循环,并确保你在整个目录中都保持在for循环中。

    我相当肯定,你当前的问题源于工作目录名值的变化,而你仍在使用它并导致循环中断。要解决此问题,您可以尝试以下代码:

    def shorten_folder_names(root_folder, max_length):
        with open("folder_names.csv", "w") as file:
            for dirpath, dirnames, filenames in os.walk(root_folder):
                for i in range(len(dirnames)):
                    dirname = dirnames[i]
                    old_name = os.path.join(dirpath, dirname)
    
                    if len(dirname) <= max_length:
                        continue
    
                    new_name = os.path.join(dirpath, dirname[:max_length])
    
                    os.rename(old_name, new_name)
    
                    dirnames[i] = dirname[:max_length]
    
                    file.write(f"{old_name} -> {new_name}\n")
    

    在这段代码中,我们使用for i循环来遍历目录名的数量。在循环的每次迭代中,我们都会抓取并设置我们正在查看的当前目录的名称,而不是将当前目录名称用作起始值,然后在循环中更改它。

    请注意,这里没有验证检查来确保两个文件名不相同(因为这会给你带来错误),所以你需要考虑这样做!

    希望这能有所帮助,祝你好运!