2013-11-28 9 views

Odpowiedz

8
s = '123' 
with open('out', 'w') as out_file: 
    with open('in', 'r') as in_file: 
     for line in in_file: 
      out_file.write(line.rstrip('\n') + s + '\n') 
+0

zmieniono odpowiednio, dzięki –

+0

Próbowałem tego i zamiast dodawać ciąg, umieszcza go na innej linii. Należy pamiętać, że na linii jest ip. Powinien to być łańcuch 127.0.0.1 zamiast 127.0.0.1 (return/enter). – Pcntl

+0

w prawo, niedatowana ponownie –

2
def add_str_to_lines(f_name, str_to_add): 
    with open(f_name, "r") as f: 
     lines = f.readlines() 
     for index, line in enumerate(lines): 
      lines[index] = line.strip() + str_to_add + "\n" 

    with open(f_name, "w") as f: 
     for line in lines: 
      f.write(line) 

if __name__ == "__main__": 
    str_to_add = " foo" 
    f_name = "test" 
    add_str_to_lines(f_name=f_name, str_to_add=str_to_add) 

    with open(f_name, "r") as f: 
     print(f.read()) 
8

Pamiętaj, używając operatora + komponować strun jest powolny. Zamiast tego przyłączaj listy.

output = "" 
file_name = "testlorem" 
string_to_add = "added" 

with open(file_name, 'r') as f: 
    file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()] 

with open(file_name, 'w') as f: 
    f.writelines(file_lines) 
+0

Czy może być lepiej, jeśli '' '[.join ([x.strip(), string_to_add, '\ n']) dla x in f]' ''? – lerner

Powiązane problemy