[英]How to replace string in original file with string from new file in 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())
在您的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
不是字符串,它是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
您需要調用match.group()
以獲取已匹配的字符串:
>>> re.sub(r'[a-z]+', match.group(), 'eggs')
'spam'
總結一下:
match
的輸出處理不為None
match.group()
作為替換字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.