使用其他名称将文件复制到同一目录

Kit*_*Kit 10 python directory path shutil

我需要使用其他名称复制同一目录中的所有html文件,我需要浏览源目录中的所有目录.

这是我的代码到目前为止,

import os
import shutil
os.chdir('/') 

dir_src = ("/home/winpc/test/copy/")

for filename in os.listdir(dir_src):
    if filename.endswith('.html'):
        shutil.copy( dir_src + filename, dir_src)
    print(filename)
Run Code Online (Sandbox Code Playgroud)

fra*_*ang 8

import os
import shutil

def navigate_and_rename(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate_and_rename(s)
        else if s.endswith(".html"):
            shutil.copy(s, os.path.join(src, "newname.html"))    

dir_src = "/home/winpc/test/copy/"
navigate_and_rename(dir_src)
Run Code Online (Sandbox Code Playgroud)

说明

浏览源文件夹中的所有文件,包括子文件夹

import os
def navigate(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate(s)
        else:
            # Do whatever to the file
Run Code Online (Sandbox Code Playgroud)

使用新名称复制到同一文件夹

import shutil
shutil.copy(src_file, dst_file)
Run Code Online (Sandbox Code Playgroud)

参考

结帐我的回答另一个问题。