0

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!

4
  • 5
    Define it's not working. How does it not work? Why does it not work - what doesn't work as intended? Are you receiving any errors? Commented Nov 14, 2016 at 5:51
  • 1
    What do you mean by it's not working? What's the actual problem you are facing? Commented Nov 14, 2016 at 5:51
  • Have you made sure your script is executable and your file has accessible permissions. Commented Nov 14, 2016 at 5:58
  • @AndrewLi it's just don't work, no errors, it's just don't replace as I expected Commented Nov 14, 2016 at 13:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I tried but this isn't working, it's not returning any error when I run my script it's just not replacing
Probably because you still are writing line, not new line... This is an easy process to debug if you'd just print the values. Get it working before you change your output source
Thank you, when doing so it deletes the line first line of my .txt leaving just the replaced item. Do you know why is it happening?
I'm not sure what you are seeing, but, 1) 'r+' can be removed from the first file. 2) Your code is hard to debug because you completely overwrite the initial file. Try writing to a different one

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.