【问题标题】:How to change the file extension in files in a list如何更改列表中文件的文件扩展名
【发布时间】:2019-09-23 06:06:13
【问题描述】:

我有这段代码用于打开包含这些目录的文件夹。其中一些具有扩展名 html,但不是全部。如何更改我的三个子目录中没有 .html 扩展名 html 的所有文件?

from os import walk
mypath = ("/directory/path/to/folder")
f = []
for (dirpath,dirnames,filenames) in walk(mypath):
    f.extend(filenames)
    print(f)

【问题讨论】:

  • 任何答案对您有帮助吗?如果是,请将其中一项标记为已接受。这样您就可以帮助其他有相同问题的人。

标签: python list subdirectory os.walk


【解决方案1】:

如果您使用的是 Python 3.4 或更高版本,请考虑使用 pathlib

以下是解决您的问题的方法:

from pathlib import Path

mypath = Path('/directory/path/to/folder')

for f in mypath.iterdir():
    if f.is_file() and not f.suffix:
        f.rename(f.with_suffix('.html'))

如果您还需要下到子目录,可以使用Path.glob() 方法递归列出所有目录,然后处理该目录中的每个文件。像这样的:

from pathlib import Path

mypath = Path('/directory/path/to/folder')

for dir in mypath.glob('**'):
    for f in dir.iterdir():
        if f.is_file() and not f.suffix:
            f.rename(f.with_suffix('.html'))

这是遍历所有目录并处理所有文件的另一种方法:

from pathlib import Path

mypath = Path('/directory/path/to/folder')

for f in mypath.glob('*'):
    if f.is_file() and not f.suffix:
        f.rename(f.with_suffix('.html'))

使用带有两个星号的Path.glob() 将列出所有子目录,而仅使用一个星号将列出该路径下的所有内容。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    用你的路径调用这个函数。

    import os
    import os.path
    
    
    def ensure_html_suffix(top):
        for dirpath, _, filenames in os.walk(top):
            for filename in filenames:
                if not filename.endswith('.html'):
                    src_path = os.path.join(dirpath, filename)
                    os.rename(src_path, f'{src_path}.html')
    

    【讨论】:

      【解决方案3】:

      首先,编写一个图片路径生成器,函数如下。

      import os
      
      def getimagepath(root_path):
          for root,dirs,filenames in os.walk(root_path):
              for filename in filenames:
                  yield(os.path.join(root,filename))
      

      在函数中输入您的文件夹路径。然后运行 ​​for 循环检查名称是否以 html 结尾,然后使用 os.rename 更改名称

      paths = getimagepath("............................")
      for path in paths:
          if not path.endswith('.html'):
               os.rename(path,path+'.html')
      

      【讨论】:

      • 使用if not path.endswith('.html') 可能会更好。还要检查. 以及将你得到的文件名像mynamehtml
      【解决方案4】:
      ff = []
      for (dirpath,dirnames,filenames) in os.walk(mypath):
          for f in filenames:
              if not f.endswith(".html"): #check if filename does not have html ext
                  new_name = os.path.join(dirpath,f+".html")
                  os.rename(os.path.join(dirpath,f),new_name) #rename the file
                  ff.append(f+".html")
              else:
                  ff.append(f)
          print(ff)
      

      【讨论】:

        【解决方案5】:

        如果您只想重命名特定后缀,请执行以下操作:

        from pathlib import Path
        
        path = Path('./dir')
        
        for f in path.iterdir():
            if f.is_file() and f.suffix in ['.txt']:
                f.rename(f.with_suffix('.md'))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-05-20
          • 2023-04-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-19
          相关资源
          最近更新 更多