pythonbegineer pythonbegineer - 1 year ago 94
Python Question

How to write in Python from a text file

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

with open('address.txt','w') as file:

what I'm doing wrong? it's not working.

Answer Source

Strings are immutable. line.replace returns a new string, not literally replaces it.

new_line = line.replace

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download