Python 如何替换文件中的字符串?
我在两个相似的文件中有两个数字。有一个Python 如何替换文件中的字符串?,python,Python,我在两个相似的文件中有两个数字。有一个new.txt和original.txt。它们都有相同的字符串,除了一个数字。new.txt有一个字符串,上面写着boothNumber=“3”。original.txt有一个字符串,上面写着boothNumber=“1” 我希望能够阅读new.txt,从中选择数字3并替换original.txt中的数字1 有什么建议吗?这就是我正在尝试的 import re # used to replace string import sys # some of th
new.txt
和original.txt
。它们都有相同的字符串,除了一个数字。new.txt
有一个字符串,上面写着boothNumber=“3”
。original.txt
有一个字符串,上面写着boothNumber=“1”
我希望能够阅读new.txt
,从中选择数字3并替换original.txt
中的数字1
有什么建议吗?这就是我正在尝试的
import re # used to replace string
import sys # some of these are use for other code in my program
def readconfig():
with open("new.text") as f:
with open("original.txt", "w") as f1:
for line in f:
match = re.search(r'(?<=boothNumber=")\d+', line)
for line in f1:
pattern = re.search(r'(?<=boothNumber=")\d+', line)
if re.search(pattern, line):
sys.stdout.write(re.sub(pattern, match, line))
更新
我试过:
def readconfig(original_txt_path="original.txt",
new_txt_path="new.txt"):
with open(new_txt_path) as f:
for line in f:
if not ('boothNumber=') in line:
continue
booth_number = int(line.replace('boothNumber=', ''))
# do we need check if there are more than one 'boothNumber=...' line?
break
with open(original_txt_path) as f1:
modified_lines = [line.startswith('boothNumber=') if not line
else 'boothNumber={}'.format(booth_number)
for line in f1]
with open(original_txt_path, mode='w') as f1:
f1.writelines(modified_lines)
我得到一个错误:
booth_number = int(line.replace('boothNumber=', ''))
ValueError: invalid literal for int() with base 10: '
(workstationID="1" "1" window=1= area="" extra parts of the line here)\n
workstationID=“1”之后的“1”是boothNumber=“”通常会出现的位置。当我打开original.txt时,我看到它实际上没有改变任何东西
更新3
这是我的全部代码。注意,文件名已更改,但我仍在尝试执行相同的操作。这是我的另一个想法或修订版,但仍然不起作用:
import os
import shutil
import fileinput
import re # used to replace string
import sys # prevents extra lines being inputed in config
# example: sys.stdout.write
def convertconfig(pattern):
source = "template.config"
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
match = r'(?<=boothNumber=")\d+'
sys.stdout.write(re.sub(match, pattern, line))
def readconfig():
source = "bingo.config"
pattern = r'(?<=boothNumber=")\d+' # !!!!!!!!!! This probably needs fixed
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
if re.search(pattern, line):
fileinput.close()
convertconfig(pattern)
def copyfrom(servername):
source = r'//' + servername + '/c$/remotedirectory'
dest = r"C:/myprogram"
file = "bingo.config"
try:
shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))
except:
print ("Error")
readconfig()
# begin here
os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
for servername in f:
copyfrom(servername.strip())
要查找
boothNumber
值,我们可以使用下一个正则表达式(选中)
(?要查找boothNumber
值,我们可以使用下一个正则表达式(选中)
(?您正在写入stdout而不是文件。您应该以write方式显式打开new.txt
,以read方式显式打开original.txt
。您不需要正则表达式。我使用re是因为我实际上从计算机列表导入了许多配置。它们都有不同的启动编号,因此我正在每个配置中搜索模式以查找这些编号有没有更好的替代方法呢?我把“with open(new.txt)”、“r”放在那里,但我仍然会遇到相同的错误。open(“original.txt”、“w”)
…你不能读取该文件,正如你所说的错误——“它们都有相同的信息,除了一个数字。”然后你也要替换这个数字。那你为什么不把new.txt复制到original.txt呢?对不起,我需要解决这个问题。它们是稍微不同的文件。它们都有相同的字符串,上面写着“boothNumber=“x”)'其中x是一个整数。您正在写入stdout而不是一个文件。您应该以写入方式显式打开new.txt
,以读取方式显式打开original.txt
。您不需要正则表达式。我使用re是因为我实际上从计算机列表中导入了许多配置。它们都有不同的启动编号,所以我在每个配置中搜索模式我想找到那些数字,每次都用它们替换我的original.text。有更好的替代方法吗?我把“with open(new.txt”,“r”)放在那里,我仍然得到相同的错误。open(“original.txt”,“w”)
…你不能读取该文件,正如错误所说的-“它们都有相同的信息,除了一个数字。”然后你也要替换这个数字。那你为什么不把new.txt复制到original.txt呢?很抱歉,我需要修复这个问题。它们是稍微不同的文件。它们都有相同的字符串,上面写着‘boothNumber=“x”)'其中x是一个整数。有没有办法用line.contains代替line.startwith?它不起作用,但我认为这是因为同一行上还有其他随机数据作为boothNumber=“x”。这些行实际上不是以该字符串开头的。对不起,我应该在第行中指定它。可能是“if(boothNumber=”)“?我在我的帖子顶部添加了一条附加注释,解释了我现在遇到的错误。@Prox:我很高兴有一种方法可以执行line.contains而不是line.startwith?它不起作用,但我认为这是因为同一行上还有其他随机数据与boothNumber=“x”。行实际上不是以该字符串开头的。对不起,我应该指定它。可能是“if(boothNumber=”)在行中?”我在我的帖子顶部添加了一条附加注释,解释了我现在遇到的错误。@Prox:我很高兴
boothNumber="r'(?<=boothNumber=")\d+'"
boothNumber="2"
(?<=\sboothNumber=\")(\d+)(?=\")
import re
import sys # some of these are use for other code in my program
BOOTH_NUMBER_RE = re.compile('(?<=\sboothNumber=\")(\d+)(?=\")')
search_booth_number = BOOTH_NUMBER_RE.search
replace_booth_number = BOOTH_NUMBER_RE.sub
def readconfig(original_txt_path="original.txt",
new_txt_path="new.txt"):
with open(new_txt_path) as f:
for line in f:
search_res = search_booth_number(line)
if search_res is None:
continue
booth_number = int(search_res.group(0))
# do we need check if there are more than one 'boothNumber=...' line?
break
else:
# no 'boothNumber=...' line was found, so next lines will fail,
# maybe we should raise exception like
# raise Exception('no line starting with "boothNumber" was found')
# or assign some default value
# booth_number = -1
# or just return?
return
with open(original_txt_path) as f:
modified_lines = []
for line in f:
search_res = search_booth_number(line)
if search_res is not None:
line = replace_booth_number(str(booth_number), line)
modified_lines.append(line)
with open(original_txt_path, mode='w') as f:
f.writelines(modified_lines)
# Preparation
with open('new.txt', mode='w') as f:
f.write('some\n')
f.write('<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')
with open('original.txt', mode='w') as f:
f.write('other\n')
f.write('<jack Fill workstationID="1" boothNumber="23" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')
# Invocation
readconfig()
# Checking output
with open('original.txt') as f:
for line in f:
# stripping newline character
print(line.rstrip('\n'))
other
<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">