【问题标题】:Copy files to same directory with another name将文件复制到另一个名称的同一目录
【发布时间】:2017-12-11 23:56:01
【问题描述】:

我需要用另一个名称复制同一目录中的所有 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)

【问题讨论】:

  • 所以基本上重命名每个文件? os.renameglob 可能会有所帮助
  • 其实我不需要重命名。我需要保持原来的文件不变。我需要用另一个名字复制到同一个文件夹
  • 为什么不发出shell命令? findcopy 函数都有递归开关,可以缓解这个问题。

标签: python path directory shutil


【解决方案1】:

解决方案

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)

说明

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

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

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

import shutil
shutil.copy(src_file, dst_file)

参考

查看我的answer 以了解另一个问题。

【讨论】:

  • 我发现shutil 很有用。
猜你喜欢
  • 1970-01-01
  • 2012-02-15
  • 2018-03-13
  • 2014-12-20
  • 1970-01-01
  • 2013-06-01
  • 2020-06-22
  • 2014-08-12
相关资源
最近更新 更多