简体   繁体   English

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

[英]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 : 这是我想做的事情:

  • Prompt the user to insert an nlps version and ncs version (both are just server builds) 提示用户插入nlps版本和ncs版本(均为服务器内部版本)
  • Get all the filenames ending in .properties in a specified folder 获取指定文件夹中所有以.properties结尾的文件名
  • Read those files to find the old nlps and ncs version 阅读这些文件以查找旧的nlps和ncs版本
  • Replace, in the same .properties files, the old nlps and ncs versions by the ones given by the user 相同的 .properties文件中,将旧的nlps和ncs版本替换为用户指定的版本

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.36.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.

相关问题 Python文件删除PermissionError:[WinError 32] - Python file delete PermissionError: [WinError 32] winError 32权限错误,删除带有scrapy的文件 - winError 32 permission error on deleting file with scrapy Python:[WinError 32]问题 - Python: [WinError 32] issue 如何解决这个 python 错误 - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: - How to tackle this python error - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 试图用python删除文件,但我得到WinError 32权限错误 - Trying to delete file with python but I'm getting WinError 32 Permission Error Python 3 删除目录时出错 [WinError 32] 该进程无权访问该文件,因为它正被另一个进程使用 - Python 3 Error deleting directory [WinError 32] The process does not have access to the file because it is being used by another process 获取 Python 错误 --&gt;PermissionError: [WinError 32] 进程无法访问该文件,因为它正被另一个进程使用 - Getting Python error -->PermissionError: [WinError 32] The process cannot access the file because it is being used by another process 带有python和fileinput的Unicode文件 - Unicode file with python and fileinput 使用文件输入 python 模块从文件中读取行时出现“'NoneType' object 不可迭代”错误 - “ 'NoneType' object is not iterable” error when using fileinput python module to read lines from file 文件未找到错误:[WinError 2] Python 目录错误 - File Not Found Error:[WinError 2] Python Directory Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM