简体   繁体   中英

fileinput error (WinError 32) when replacing string in a file with Python

After looking for a large amount of time, I still can't seem to find an answer to my problem (I am new to python).

Here is what I'm trying to do :

  • Prompt the user to insert an nlps version and ncs version (both are just server builds)
  • Get all the filenames ending in .properties in a specified folder
  • Read those files to find the old nlps and ncs version
  • Replace, in the same .properties files, the old nlps and ncs versions by the ones given by the user

Here is my code so far :

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()

In the .properties files, the versions would be written like :

NlpsVersion=6.3.107.3
NcsVersion=6.4.000.29

I am able to get old_nlpsversion and old_ncsversion to be 6.3.107.3 and 6.4.000.29 . The problem occurs when I try to replace the old versions with the ones the user inputed. I get the following error :

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'

It may be that my own process is the one using the file, but I can't figure out how to replace, in the same file, the versions without error. I've tried figuring it out myself, there are a lot of threads/resources out there on replacing strings in files, and i tried all of them but none of them really worked for me (as I said, I'm new to Python so excuse my lack of knowledge).

Any suggestions/help is very welcome,

You are not releasing the file. You open it readonly and then attempt to write to it while it is still open. A better construct is to use the with statement. And you are playing fast and loose with your variable scope. Also watch your case with variable names. Fileinput maybe a bit of overkill for what you are trying to do.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM