使用Python替换文件中的字符串时的fileinput错误(WinError 32)

时间:2017-10-04 18:03:41

标签: python file replace

在寻找了大量的时间后,我似乎无法找到问题的答案(我是python的新手)。

这是我正在尝试做的事情:

  • 提示用户插入nlps版本和ncs版本(两者都只是服务器版本)
  • 获取以指定文件夹中的.properties结尾的所有文件名
  • 阅读这些文件以查找旧的nlps和ncs版本
  • 相同的 .properties文件中,将旧的nlps和ncs版本替换为用户提供的版本

到目前为止,这是我的代码:

import glob, os
import fileinput

nlpsversion = str(input("NLPS Version : "))
ncsversion = str(input("NCS Version : "))

directory = "C:/Users/x/Documents/Python_Test"


def getfilenames():
    filenames = []
    os.chdir(directory)
    for file in glob.glob("*.properties"):
        filenames.append(file)
    return filenames

properties_files = getfilenames()

def replaceversions():
    nlpskeyword = "NlpsVersion"
    ncskeyword = "NcsVersion"

    for i in properties_files:
        searchfile = open(i, "r")
        for line in searchfile:

            if line.startswith(nlpskeyword):
                old_nlpsversion = str(line.split("=")[1])

            if line.startswith(ncskeyword):
                old_ncsversion = str(line.split("=")[1])

        for line in fileinput.FileInput(i,inplace=1):
            print(line.replace(old_nlpsversion, nlpsVersion))


replaceversions()

在.properties文件中,版本的编写方式如下:

NlpsVersion=6.3.107.3
NcsVersion=6.4.000.29

我能够将old_nlpsversion和old_ncsversion变为 6.3.107.3 6.4.000.29 。当我尝试将旧版本替换为用户输入的版本时,会出现问题。我收到以下错误:

C:\Users\X\Documents\Python_Test>python replace.py
NLPS Version : 15
NCS Version : 16
Traceback (most recent call last):
  File "replace.py", line 43, in <module>
    replaceversions()
  File "replace.py", line 35, in replaceversions
    for line in fileinput.FileInput(i,inplace=1):
  File "C:\Users\X\AppData\Local\Programs\Python\Python36-
32\lib\fileinput.py", line 250, in __next__
    line = self._readline()
  File "C:\Users\X\AppData\Local\Programs\Python\Python36-
32\lib\fileinput.py", line 337, in _readline
    os.rename(self._filename, self._backupfilename)
PermissionError: [WinError 32] The process cannot access the file because it 
is being used by another process: 'test.properties' -> 'test.properties.bak'

可能是我自己的进程是使用该文件的进程,但我无法弄清楚如何在同一文件中替换没有错误的版本。我已经尝试过自己弄清楚,有很多线程/资源在那里替换文件中的字符串,我尝试了所有这些但是没有一个真的对我有效(正如我所说,我是Python新手请原谅我缺乏知识。)

非常欢迎任何建议/帮助,

1 个答案:

答案 0 :(得分:1)

您没有发布该文件。您只读它打开它,然后尝试在它仍然打开时写入它。更好的构造是使用 with 语句。而且你在变幅范围内玩得很快。还要使用变量名称来观察您的情况。对于你想要做的事情,文件输入可能有点过分。

import glob, os
import fileinput

def getfilenames(directory):
    filenames = []
    os.chdir(directory)
    for file in glob.glob("*.properties"):
        filenames.append(file)
    return filenames

def replaceversions(properties_files,nlpsversion,ncsversion):
    nlpskeyword = "NlpsVersion"
    ncskeyword = "NcsVersion"

    for i in properties_files:
        with open(i, "r") as searchfile:
            lines = []
            for line in searchfile: #read everyline
                if line.startswith(nlpskeyword): #update the nlpsversion
                    old_nlpsversion = str(line.split("=")[1].strip())
                    line = line.replace(old_nlpsversion, nlpsversion)
                if line.startswith(ncskeyword): #update the ncsversion
                   old_ncsversion = str(line.split("=")[1].strip())
                   line = line.replace(old_ncsversion, ncsversion)
                lines.append(line)  #store changed and unchanged lines
        #At the end of the with loop, python closes the file

        #Now write the modified information back to the file.
        with open(i, "w") as outfile:  #file opened for writing
            for line in lines:
                outfile.write(line+"\n")
        #At the end of the with loop, python closes the file

if __name__ == '__main__':
    nlpsversion = str(input("NLPS Version : "))
    ncsversion = str(input("NCS Version : "))

    directory = "C:/Users/x/Documents/Python_Test"
    properties_files = getfilenames(directory)

    replaceversions(properties_files,nlpsversion,ncsversion)