【发布时间】:2021-02-13 18:42:54
【问题描述】:
问题
大家好,
在文本文件中我需要用另一个替换未知字符串,
首先要找到它,我需要找到它之前的行'name Blur2' 因为'xpos'有很多行开头:
name Blur2
xpos 12279 # 12279 is the end of line to find and put in a variable
获取未知字符串的代码:
#string to find:
keyString = ' name Blur2'
f2 = open("output_file.txt", 'w+')
with open("input_file.txt", 'r+') as f1:
lines = f1.readlines()
for i in range(0, len(lines)):
line = lines[i]
if keyString in line:
nextLine = lines[i + 1]
print ' nextLine: ',nextLine #result: nextLine: xpos 12279
number = nextLine.rsplit(' xpos ', 1)[1]
print ' number: ',number #result: number: 12279
#convert string to float:
newString = '{0}\n'.format(int(number)+ 10)
print ' newString: ',newString #result: newString: 12289
f2.write("".join([nextLine.replace(number, str(newString))])) #this line isn't working
f1.close()
f2.close()
所以,我完全改变了方法,但最后一行:f2.write... 没有按预期工作,有人知道为什么吗?
再次感谢您的帮助:)
【问题讨论】:
-
最后 5 个字符
line[-5:] -
处理所有行,不包含搜索字符串
Blur2时复制,如果包含Blur2设置布尔值,如果布尔值设置在下一行,则替换并重置布尔值。也使用上下文管理器:with open("last_file.txt", 'r+') as f1: -
谢谢,方法:line[-5:]is 与我的代码完美配合:f2.write("".join([i.replace(i[-10:], newPad) if keyString in i else i for i in f1.readlines()]))
-
对于替换,不幸的是我需要在替换之前记录它,我不知道如何,我正在尝试通过拆分来获取它...
-
不要以大写开头的变量,在 Python 约定中是类名