创建新目录和移动文件时出错

时间:2017-07-28 22:28:24

标签: python shutil

我有一个脚本,在创建一堆文件后,将创建一个新目录,然后将这些文件移动到该新目录中。它起初工作但突然间我收到了一个错误,我不知道它为什么会出现。 编辑:我为那些想知道的人添加了我之前的代码(全部在同一个模块中)。

我的代码:

import os
import shutil
mydir = os.getcwd()

def edit_and_rename_files():
    f = filelist() # an earlier script that just makes a list of files I care about
    for item in f:
        with open(item, "r+") as id_file:
            for line in id_file:
               does something
              return my_dict # just a dict with ids I want to rename

        with open(item, "r+") as infile:
            content = infile.readlines()
            new_content = []
            for line in content: # going to copy and rewrite some lines
                new_line = line
                for original_id, new_id in my_dict.items():
                    new_line = new_line.replace(original_id, new_id + "\n")
                new_content.append(new_line)

       with open(item+"_renamed.fa", "w") as outfile:
           for line in new_content:
               outfile.write(line)

edit_and_rename_files()                 


def move_files():
    renamed_dir = mydir + "\\renamed"
    if not os.path.exists(renamed_dir):
        os.mkdir(renamed_dir)
    else:
        print "This directory already exists. Will move the files into this directory anyways."

   for root, dirs, files in os.walk(mydir):
        for fname in files:
            if fname.endswith("_renamed.fa"):
                shutil.move(fname, renamed_dir)

move_files()

这个脚本执行并且文件被创建并且实际上移动正常(当我打开文件时没有错误),但是我仍然会收到一个错误,这让我感到烦恼。

Traceback (most recent call last):
  File "rename_concatenated_file_ALL.py", line 59, in <module>
    move_files()
  File "rename_concatenated_file_ALL.py", line 58, in move_files
   shutil.move(fname, renamed_dir)
File "C:\Python27\lib\shutil.py", line 292, in move
   raise Error, "Destination path '%s' already exists" % real_dst
shutil.Error: Destination path 'C:\Users\MyName\Desktop\RenamingWork\atp_main\renamed\atp_main_renamed.fa' already exists

0 个答案:

没有答案