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

时间:2017-06-03 02:02:02

标签: python

我有一个原始配置文件,其中包含一个字符串:

boothNumber="5"

在我的程序中,我从另一台计算机上获取了类似的配置。这个类似的配置有一个字符串:

boothNumber="1"

我想读取新的数字1,并用数字1替换原始配置(替换5)。

我的程序中出现错误:

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

有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

readConfig函数中,此行执行搜索:

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

并且match的值在此行中使用:

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

这里有两个问题。首先,如果搜索不成功,match将为None,导致您报告的例外:

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

其次,如果match不是None,您尝试将match本身用作替换字符串,但match不是字符串,而是{{3} }}:

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

您需要致电match.group()以获取已匹配的字符串:

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

总结:

  • 调整match上的输出处理不是None
  • 使用match.group()作为替换字符串