Python - 用连续的数字在特定字符串后面添加一行
问题描述:
我确实遇到了一个小问题,我无法在Python中解决,iam不太熟悉这些代码命令,这就是其中一个原因我。Python - 用连续的数字在特定字符串后面添加一行
例如,当我有一个文本文件是这样的:
Indicate somename X1
Random qwerty
Indicate somename X2
random azerty
Indicate somename X3
random qwertz
Indicate somename X4
random asdfg
Indicate somename X5
我想提出一个脚本来获取特定值的背后,是这样的:
Indicate somename X1 value = 500
Random qwerty
Indicate somename X2 value = 500
random azerty
Indicate somename X3 value = 500
random qwertz
Indicate somename X4 value = 500
random asdfg
Indicate somename X5 value = 500
我已经尝试过一个这样的脚本:
def replace_score(file_name, line_num, text):
f = open(file_name, 'r')
contents = f.readlines()
f.close()
contents[line_num] = text+"\n"
f = open(file_name, "w")
contents = "".join(contents)
f.write(contents)
f.close()
replace_score("file_path", 10, "replacing_text")
但我不能让它按照我希望的方式工作。
我希望有人能帮助我,
问候,
答
with open('sample') as fp, open('sample_out', 'w') as fo:
for line in fp:
if 'Indicate' in line:
content = line.strip() + " = 500"
else:
content = line.strip()
fo.write(content + "\n")
答
with open('/tmp/content.txt') as f: # where: '/tmp/content.txt' is the path of file
for i, line in enumerate(f.readlines()):
line = line.strip()
if not (i % 2):
line += ' value = 500'
print line.strip()
# Output:
Indicate somename X1 value = 500
Random qwerty
Indicate somename X2 value = 500
random azerty
Indicate somename X3 value = 500
random qwertz
Indicate somename X4 value = 500
random asdfg
Indicate somename X5 value = 500
答
使用 '重' 模块
如。
if re.match(r'Indicate somename [A-Z][0-2]', line):
modified = line.strip() + ' value = XXX'
,如果你想需要修改就地输入文件, 读项文件中的缓冲区,然后写回结果。
+0
很高兴知道[A-Z]命令存在!这些数字都非常有趣,我不知道。 有没有可能的方法给予,比方说100,不同的“表示某个名称”不同的个人价值? – Mennoo
非常感谢你,这个对我来说工作得很好。 我已经有了值500,用%d命令表示数字。 然而,接下来我要做的是将所有“idicate somename X”放在一个数组中,因为这些值对于每个单独的值应该是不同的,并且会有几百个这样的值,这是我的下一个challange。 – Mennoo