2016-09-21 43 views
0

我確實遇到了一個小問題,我無法在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") 

但我不能讓它按照我希望的方式工作。

我希望有人能幫助我,

問候,

回答

0
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") 
+0

非常感謝你,這個對我來說工作得很好。 我已經有了值500,用%d命令表示數字。 然而,接下來我要做的是將所有「idicate somename X」放在一個數組中,因爲這些值對於每個單獨的值應該是不同的,並且會有幾百個這樣的值,這是我的下一個challange。 – Mennoo

0
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 
0

使用 '重' 模塊

如。

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

,如果你想需要修改就地輸入文件, 讀項文件中的緩衝區,然後寫回結果。

+0

很高興知道[A-Z]命令存在!這些數字都非常有趣,我不知道。 有沒有可能的方法給予,比方說100,不同的「表示某個名稱」不同的個人價值? – Mennoo

相關問題