【问题标题】:Copy directory from path into current directory将目录从路径复制到当前目录
【发布时间】:2020-06-02 06:54:42
【问题描述】:

以下 python 代码获取文件特定实例的文件路径列表,以将它们复制到当前目录中,路径名称在标题中:

python3 find.py --copy zz /Users/apt/testdir a.txt 
/Users/apt/testdir/d1/a.txt 
/Users/apt/testdir/d1/d3/a.txt 
/Users/apt/testdir/d1/d3/d4/a.txt 
/Users/apt/testdir/d1/d3/d5/a.txt
$ ls zz
Users_apt_testdir_d1_a.txt     
Users_apt_testdir_d1_d3_d4_a.txt
Users_apt_testdir_d1_d3_a.txt  
Users_apt_testdir_d1_d3_d5_a.txt

一切正常,但我的复制功能:

def copy(f, new_dir):
   file_name=str(f[1:])
   file_name=file_name.replace('/', "_")
   file_path=os.path.join(new_dir, file_name)
   shutil.copy(file_path, new_dir)                                                                                         
   os.chdir(os.path.abspath(new_dir))
   os.rename(list(os.path.split(f))[1], file_name)

FileNotFoundError: [Errno 2] No such file or directory: "zz/['_u_macole_testdir_d1_d3_a.txt', '_u_macole_testdir_d1_d3_d4_a.txt', '_u_macole_testdir_d1_d3_d5_a.txt']

【问题讨论】:

    标签: python directory copy


    【解决方案1】:

    错误是不言自明的,filenew_dir 没有好的类型。由于file 是一个列表,因此您需要迭代并每次调用copy: 类似的东西

    def copy(f, new_dir):
       file_name=str(f[1:])
       file_name=file_name.replace('/', "_")
       file_path=os.path.join(new_dir, file_name)
       shutil.copy(file_path, new_dir)                                                                                         
       os.chdir(os.path.abspath(new_dir))
       os.rename(f, file_name)
    
    for i in f:
       copy(i, new_dir)
    

    【讨论】:

    • @Matt 在那之后我更新了我的答案,我也不确定是否需要前导下划线,如果不是,你可能想把 file_name=str(f[2:]) 代替 file_name=str(f[1:])
    • 这会替换整行吗? os.rename(list(os.path.split(f))[1], file_name)
    • 我不确定你在做什么,但 os.rename 将路径作为参数,而不是列表,我用你的完整代码更新我的答案
    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 2022-01-21
    • 1970-01-01
    • 2014-08-16
    • 2023-04-02
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多