当该文件已存在时无法创建文件使用Python观察到错误

时间:2018-02-28 12:42:28

标签: python python-2.7 file

我试图重命名文件,然后打开它并修改数据,但我观察到以下错误 [错误183]当该文件已存在时无法创建文件  我的代码在这里:

def copy_and_replace_new_files(path, list_of_dictionary):
    ''' get to working directory'''
    os.chdir(path)

    ''' get each dictionary
        get all key values
        start moving files to new destination
        this will be with new name'''
    for item in iter(list_of_dictionary):
        ''' join path and source file
        copy to destination and rename'''
        src_dir = os.curdir
        dst_dir = os.path.join(os.curdir, "new")
        src_file = os.path.join(src_dir, item['filename'])
        shutil.copy(src_file, dst_dir)

        dst_file = os.path.join(dst_dir, item['filename'])  # old file name
        new_file_name = os.path.splitext(item['filename'])[0]
        new_file_name = new_file_name + '_new' + '.txt'
        os.rename(dst_file, new_file_name)
        ''' Find and Replace with Pattern'''
        for newline in fileinput.FileInput(new_file_name, inplace=1):
            pattern = item['table']
            pattern = str(pattern).rstrip()
            newline = newline.replace(str(pattern), str(pattern+'_new'))
            print(newline.rstrip())

你能告诉我哪里出错了。

1 个答案:

答案 0 :(得分:0)

    import os
    file_list = os.listdir(r"C:\Users\ساشلاشى\Desktop\game")
    save_ = os.getcwd()
    os.chdir("C:\Users\ساشلاشى\Desktop\game")
    for file_name in file_list:
         print("old name = "+file_name)
         print("new name = "+file_name.translate(None,"0123456789"))
         os.rename(file_name,file_name.translate(None,"0123456789"))
    os.chdir(save_)