简体   繁体   English

如何用Python中新文件中的字符串替换原始文件中的字符串

[英]How to replace string in original file with string from new file in Python

I have an original config file that has a string: 我有一个包含字符串的原始配置文件:

boothNumber="5"

In my program, I grab a similar config from another computer. 在我的程序中,我从另一台计算机上获取了类似的配置。 This similar config has a string: 这个类似的配置有一个字符串:

boothNumber="1"

I want to read the new number which is 1 and replace the original config with the number 1(replaces 5). 我想读取新的数字1,并将原始配置替换为数字1(代替5)。

I am getting an error in my program that says: 我的程序出现错误,提示:

TypeError: coercing to str: need a bytes-like object, NoneType found

Any ideas? 有任何想法吗?

import os
import shutil
import fileinput
import pypyodbc
import re                                     # used to replace string
import sys                                    # prevents extra lines being inputed in config


def readconfig(servername):
    destsource = 'remote.config'                                            # file that I grabbed from remote computer
    template = 'original.config'                                        # original config
    for line in open(destsource):                                       # open new config
        match = re.search(r'(?<=boothNumber=")\d+', line)               #find a number after a certain string and name it 'match'

        with fileinput.FileInput(template, inplace=True, backup='.bak') as file:  # open original config
            for f2line in file:
                pattern = r'(?<=boothNumber=")\d+'                      # find number after certain string and name it 'pattern'


                if re.search(pattern, f2line):                          # if line has 'pattern'
                    sys.stdout.write(re.sub(pattern, match, f2line))    # replace 'pattern' number with number from 'match'
                    fileinput.close()



def copyfrom(servername):
    # copy config from server


    source = r'//' + servername + '/c$/configdirectory'
    dest = r"C:/myprogramdir"
    file = "remote.config"
    try:
        shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))
        # you can't just use shutil when copying from a remote computer.  you have to also use os.path.join
    except:
        copyerror()

    readconfig(servername)



os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:       # list of computer names
    for servername in f:

        copyfrom(servername.strip())

In your readConfig function, this line performs a search: 在您的readConfig函数中,此行执行搜索:

match = re.search(r'(?<=boothNumber=")\\d+', line)

and the value of match is used in this line: 在此行中使用match的值:

sys.stdout.write(re.sub(pattern, match, f2line))

There are two problems here. 这里有两个问题。 Firstly, if the search is unsuccessful match will be None , causing to the exception that you report: 首先,如果搜索失败,则matchNone ,从而导致您报告以下异常:

 >>> re.sub(r'[a-z]+', None, 'spam')
Traceback (most recent call last):
...
TypeError: decoding to str: need a bytes-like object, NoneType found

Secondly, if match is not None , you are trying to use match itself as replacement string, but match is not a string, it's a match object : 其次,如果match不为None ,则尝试将match本身用作替换字符串,但是match不是字符串,它是match对象

>>> match = re.search(r'[a-z]+', 'spam')
>>> match
<_sre.SRE_Match object; span=(0, 4), match='spam'>  # <=== not a string!
>>> re.sub(r'[a-z]+', match, 'eggs')
Traceback (most recent call last):
  ...
TypeError: decoding to str: need a bytes-like object, _sre.SRE_Match found

You need to call match.group() to get the string that has been matched: 您需要调用match.group()以获取已匹配的字符串:

>>> re.sub(r'[a-z]+', match.group(), 'eggs')
'spam'

To summarise: 总结一下:

  • condition the output processing on match not being None 条件match的输出处理不为None
  • use match.group() as the replacement string 使用match.group()作为替换字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在原始位置python中替换文件中的字符串 - Replace a string in file in it's original place python 在python中替换文件中的字符串? - Replace String from file In python? 如何替换文本文件中的字符串并将其保存到新文件中? - How to replace String in a textfile and save it to a new file? 如何打开文件,替换该文件中的字符串,然后使用Python将其写入新文件 - How can I open a file, replace a string in that file and write it to a new file using Python 如何从 CSV 文件中替换 python 中字符串的一部分? - How to replace a part of a string in python from CSV file? 如何从python中删除文本文件中的替换字符串? - How to delete replace string in text file from python? 从文件中读取字符串,将其替换,然后将其存储在新文件中。 (Python 3.x) - Read string from a file, replace it, store it in a new file. (Python 3.x) 蟒蛇; 如何替换字符串模式并保存到文件中,如何使用字符串变量将文件名从文件夹名重命名为文件名? - Python; how to replace string pattern and save to a file, rename the file by string variable from folder name to the filename? 如何替换文件中的字符串? - How to replace a string in a file? 如何使用 python 将文件中的字符串替换为变量值并将更新的内容保存为新文件 - How to replace string in a file with value of variable using python and save updated content as new file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM