Bonfel
Bonfel

Reputation: 11

python3.5.2 deleting all matching characters from a file

Given the following exemple how can i remove all "a" characters from a file that have the following content:

asdasdasd \n d1233sss \n aaa \n 123

I wrote the following solution but it does not work:

with open("testfisier","r+") as file:
    for line in file:
        for index in range(len(line)):
            if line[index] is "a":line[index].replace("a","")

Upvotes: 1

Views: 46

Answers (4)

Ajax1234
Ajax1234

Reputation: 71461

You can try this:

import re
data = open("testfisier").read()
final_data = re.sub('a+', '', data)

Upvotes: 1

user2390182
user2390182

Reputation: 73470

You can call replace on a long string. No need to call it on single chars. Also, replace does not change a string, but returns a new one:

with open("testfisier", "r+") as file:
    text = file.read()
    text = text.replace("a", "")  # replace a's in the entire text
    file.seek(0)                  # move file pointer back to start
    file.write(text)

Upvotes: 0

Kenny Chau
Kenny Chau

Reputation: 96

There weren't any changes because you didn't write it back to the file.

with open("testfisier", "r+") as file:
    for line in file:
        for index in range(len(line)):
            if line[index] is "a":
                replace_file = line[index].replace("a", "")

    # Write the changes.
    file.write(replace_file)

Or:

with open("testfisier", "r+") as f:
    f.write(f.read().replace("a", ""))

Upvotes: 2

Joel Lee
Joel Lee

Reputation: 1119

Try using regexp substitution. For instance, assuming you have read in the string and named it a_string

import re re.sub('a','',a_string,'') This would be one of many possible solutions.

Hope this helps!

Upvotes: 1

Related Questions