Python 如何更改列表中文件的文件扩展名
我有这个代码来打开包含这些目录的文件夹。其中一些具有扩展html,但并非所有。如何更改三个子目录中的所有文件,这些文件在.html中没有扩展名htmlPython 如何更改列表中文件的文件扩展名,python,list,subdirectory,os.walk,Python,List,Subdirectory,Os.walk,我有这个代码来打开包含这些目录的文件夹。其中一些具有扩展html,但并非所有。如何更改三个子目录中的所有文件,这些文件在.html中没有扩展名html 从操作系统导入漫游 mypath=(“/directory/path/to/folder”) f=[] 对于walk(mypath)中的(dirpath、dirname、filename): f、 扩展(文件名) 印刷品(f) 首先,编写一个具有以下功能的图像路径生成器 import os def getimagepath(root_path)
从操作系统导入漫游
mypath=(“/directory/path/to/folder”)
f=[]
对于walk(mypath)中的(dirpath、dirname、filename):
f、 扩展(文件名)
印刷品(f)
首先,编写一个具有以下功能的图像路径生成器
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')
使用您的路径调用此函数
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')
如果你在Python上3.4或更高,考虑使用.< /P> 以下是您的问题的解决方案:
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'))
如果您还需要走到子目录,可以使用该方法递归列出所有目录,然后处理该目录中的每个文件。大概是这样的:
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.endswith('.html'),使用
可能会更好。还要检查
以及encase,你会得到一个文件名,比如mynamehtml
这些答案对你有帮助吗?如果是,请将其中一个标记为已接受。这样你就可以帮助其他人解决同样的问题。
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'))