Python - 在特定字符串后添加一行,并带有连续数字

2024-09-28 03:13:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我确实有一个小问题我不能用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")

但我不能让它按我想要的方式工作。你知道吗

我希望有人能帮我

问候


Tags: textnamevaluecontentsrandomfilex1x2
3条回答
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

使用“re”模块

例如

 if re.match(r'Indicate somename [A-Z][0-2]', line):
     modified = line.strip() + ' value = XXX'

如果需要修改输入文件, 将条目文件读入缓冲区,然后将结果写回。你知道吗

相关问题 更多 >

    热门问题