-1

这是我分别用 mike 和 jim 替换所有出现的 kyle 和 john 的代码。

import os
import fileinput
import sys


rootdir ='C:/Users/sid/Desktop/app'
searchTerms={"kyle":"mike","john":"jim"}

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
            path=subdir+'/'+file
            for key,value in searchTerms.items():
                replaceAll(path,key,value)

这对于我创建的测试目录工作正常。当我将 rootdir 更改为我的实际 java 项目目录时,我得到了

Traceback (most recent call last):
  File "C:\Users\sid\Desktop\test_iterator.py", line 19, in <module>
    replaceAll(path,key,value)
  File "C:\Users\sid\Desktop\test_iterator.py", line 10, in replaceAll
    for line in fileinput.input(file, inplace=1):
  File "C:\Python33\lib\fileinput.py", line 261, in __next__
    line = self.readline()
  File "C:\Python33\lib\fileinput.py", line 330, in readline
    os.rename(self._filename, self._backupfilename)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:/Users/sid/Desktop/app/pom.template.xml.bak'         

有人可以解释为什么我得到这个错误。我已阅读有关 os.rename() FileExistsError 的帖子,但我无法理解。有的可以详细解释一下。

4

1 回答 1

2

当您使用fileinput.input(..., inplace=1)时,输入文件被重命名,并且您的代码产生的任何输出sys.stdout都将写入具有原始文件名的新创建的文件。

fileinput因此必须首先通过添加.bak名称来重命名原始文件。但是,似乎已经存在这样的文件。可能您之前的代码中存在错误,并且从未删除过备份文件。

确认它C:/Users/sid/Desktop/app/pom.template.xml.bak不包含您想要保留的任何内容,然后将其删除或移回C:/Users/sid/Desktop/app/pom.template.xml.

但是,如果您一直遇到这种情况,那么 Python 会在自动删除备份文件时遇到问题。在 Windows 上,这通常是因为另一个进程在后台为自己的目的不断打开文件。您可以尝试在超时后删除备份文件:

import time, os

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

    time.sleep(1) # wait 1 second, then delete the backup
    os.remove(file + '.bak')

如果您的文件是只读的,请先将它们设为可写:

import os, stat

def replaceAll(file,searchExp,replaceExp):
    readonly = not os.stat(myFile)[0] & stat.S_IWRITE
    if readonly:
        os.chmod(file, stat.S_IWRITE)

    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

    if readonly:
        os.chmod(file, stat.S_IREAD)
于 2013-10-28T13:10:19.210 回答