2017-10-05 140 views
-1

我需要在文本文件的特定行中的單詞後添加字符串。原始文件是:Python - 在文件的特定行中的單詞後添加字符串

line 1: value1 
line 2: value2 
line 3: value3 
line 4: value4 
line 5: value5 

例如,我想在3號線加「NAME」剛過「行」,所以該文件將成爲:

line 1: value1 
line 2: value2 
line NAME 3: value3 
line 4: value4 
line 5: value5 

,你會怎麼做呢?

+0

你能發佈您的代碼? –

回答

0
with open(file, 'r') as f: 
    lines = [] 
    for line in f: 
     split_lines = line.split(':') 
     if split_lines[0].endswith('3') is True: 
      lines.append(split_lines[0][:-1] + NAME + split_lines[1:]) 
     else: 
      lines.append(line) 
+0

你在哪裏重寫文件? –

+0

@Stéphane只需在寫入模式下打開相同的文件並在列表行中寫入行。 –

0

我會考慮這個問題:

line_number = 3#I understood you know this. right ? 
string_to_add = "NAME"#I understood you know this. right ? 
string_to_find = "line"#I understood you know this. right ? 
filename = "toto" 
with open(filename,"r") as f: 
    s = f.readlines() 
s[line_number] = s[line_number].replace(string_to_find,string_to_find+string_to_add) 
with open(filename,"w") as f: 
    for line in s: 
     f.write(line) 

這是真的,它似乎非常低效的(也可能不是一個大文件的現實)。我會好奇看到更好的方法。

1

這將查找以「第3行:」開始的行,並僅編輯此行,保留其餘行,並將文本寫入新文件。

with open('f1.txt', 'r') as f: 
    lines = [] 
    for line in f: 
     if line.startswith("line 3:"): 
      split_line = line.split() 
      split_line.insert(split_line.index("3:"), "NAME") 
      lines.append(' '.join(split_line) + '\n') 
     else: 
      lines.append(line) 

with open('f2.txt', 'w') as f: 
    for line in lines: 
     f.write(line) 

當您運行下面的代碼,

with open('f2.txt', 'r') as f: 
    for line in f: 
     print(line, end='') 

它打印:

line 1: value1 
line 2: value2 
line NAME 3: value3 
line 4: value4 
line 5: value5 
相關問題