简体   繁体   English

如何组合这些“for”语句?

[英]How to combine these 'for' statements?

I'm writing a program that can scan root folder, directories and files and rename them so they all fit a naming convention.我正在编写一个程序,它可以扫描根文件夹、目录和文件并重命名它们,使它们都符合命名约定。

I currently have 3 for loops, one for root, dirs, files, and then I apply the os.rename() and .replace() method so change the file names.我目前有 3 个for循环,一个用于 root、dirs、files,然后我应用os.rename().replace()方法来更改文件名。 The code looks like this:代码如下所示:

    def rename_files(self):
        """ Handles the renaming of files """

        for root, dirs, files in os.walk(self._path_start):
            for _r in root:
                # Show original file name
                print(_r)
                try:
                    os.rename(_r, _r.replace(" ", "-").lower())
                except Exception:
                    pass

                try:
                    os.rename(_r, _r.replace("_", "-").lower())
                except Exception:
                    pass
                print(f"File renamed: {_r}")

            for _d in dirs:
                # Show original file name
                print(_d)
                try:
                    os.rename(_d, _d.replace(" ", "-").lower())
                except Exception:
                    pass

                try:
                    os.rename(_d, _d.replace("_", "-").lower())
                except Exception:
                    pass
                print(f"File renamed: {_d}")

            for file in files:
                # Show original file name
                print(file)
                try:
                    os.rename(file, file.replace(" ", "-").lower())
                except Exception:
                    pass

                try:
                    os.rename(file, file.replace("_", "-").lower())
                except Exception:
                    pass
                print(f"File renamed: {file}")

I'm aware there will be issues with my code, and that exceptions shouldnt be handled like that from what I've read, but I'm wondering if someone could help me make the above more concise?我知道我的代码会有问题,并且不应该像我读过的那样处理异常,但我想知道是否有人可以帮助我使上述内容更简洁? or I am open to re-writing the section a new way entirely if anyone has a suggestion?或者如果有人有建议,我愿意以全新的方式重新编写该部分?

Ideally, I'd like to be able to blend the 3 seperate for statements and then apply os.rename() and .replace() once, rather than 3 times but I've not been able to get anything to work.理想情况下,我希望能够将 3 个单独的for语句混合在一起,然后应用os.rename().replace()一次,而不是 3 次,但我无法获得任何工作。

The code will fail as soon as it makes the first rename, causing all other yields from os.walk to be different.代码在第一次重命名时就会失败,导致 os.walk 的所有其他收益都不同。 The code can get very complex and heavy on the cpu but I think the best solution is to start with the dirs and to recreate os.walk generator on every change with a while loop and then to change the actual files.代码在 cpu 上可能变得非常复杂和繁重,但我认为最好的解决方案是从目录开始,并在每次更改时使用 while 循环重新创建 os.walk 生成器,然后更改实际文件。

More optimization may be added but a sample code would look like this(not tested):可能会添加更多优化,但示例代码如下所示(未测试):

def rename_files(self):
    """ Handles the renaming of files """
    breaker=True
    while breaker:
        for root, dirs, files in os.walk(self._path_start):
            # Show original file name
            print(root,dirs,files)
            for dir in dirs:
                if " " in dir or "_" in dir:
                    dir_path=os.path.join(root,dir)
                    os.rename(dir_path,dir_path.replace(" ", "-").replace("_","-").lower())
                    break
                break
            for file in files:
                if " " in file or "_" in file:
                    file_path=os.path.join(root,file)
                    os.rename(file_path,file_path.replace(" ", "-").replace("_","-").lower())
                    print(f"File renamed: {file}") 
                breaker=False
        continue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM