简体   繁体   中英

How to delete a specific character automatically from a text file using Python?

I am trying to use a bit of code for a project to take combinations of a set of alphanumeric characters and write them into a.txt file. When I open the file from my device, it shows the following:

[aaaa
[aaab
[aaac
...
]fh52
...

The code should just be outputting the letters and numbers, no other characters and yet it still is. I can deal with the.txt file having these "artifacts" but I need a way of deleting these artifacts using Python in the future.

What I would think the code should look like:

unwanted_chars="[]"
datafile=open("Combinations.txt", 'a+')
for line in datafile:
    for char in line:
        if char in unwanted_chars:
            line.replace(char,"")

Any help on this is greatly appreciated.

You're close. First, you don't need that if statement. Second, the replace method for str doesn't alter the item in place, so your last line isn't doing anything. You'd need to read the file in, replace the characters, and then write it back out.

with open('Combinations.text') as f:
    lines=list(f)
for k, line in enumerate(lines):
    for c in unwanted_chars:
        line=line.replace(c,'')
    lines[k]=line

with open('Combinations.text','w') as f:
    f.write('\n'.join(lines))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM