[英]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: 首先,如果搜索失败,则
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
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: 总结一下:
match
not being None
match
的输出处理不为None
match.group()
as the replacement string match.group()
作为替换字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.