Reputation: 85
I'm trying to open a text file and write to the file but when doing so it's not working at all.
Here's what I have:
changeaddress = [changeaddr1, changeaddr2]
address = [address_1, address_2]
new_var = []
cur_addr = 0
with open('address.txt','r+') as file:
for line in file:
if address[cur_addr] in line:
line.replace(address[cur_addr], changeaddress[cur_addr])
cur_addr += 1
new_var.append(line)
with open('address.txt','w') as file:
file.writelines(new_var)
what I'm doing wrong? it's not working. thanks!
Upvotes: 0
Views: 73
Reputation: 191993
Strings are immutable. line.replace
returns a new string, not literally replaces it.
new_line = line.replace
...
new_var.append(new_line)
Note: storing the whole list in memory will be bad for large files. You can open two files in one with
command to read from one file, and write to another
Upvotes: 1