[英]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). 经过大量的时间后,我似乎仍然找不到解决问题的答案(我是python的新手)。
Here is what I'm trying to do : 这是我想做的事情:
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 : 在.properties文件中,版本将如下所示:
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 . 我能够将old_nlpsversion和old_ncsversion设置为6.3.107.3和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).
我尝试自己弄清楚它,有很多线程/资源可以替换文件中的字符串,我尝试了所有这些线程/资源,但没有一个真正对我有用(正如我所说,我是Python的新手)请原谅我缺乏知识)。
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.
更好的构造是使用with语句。 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.
Fileinput可能对您要执行的操作有些矫kill过正。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.