I wanted to try something seemingly easy, but I can't wrap my head around this.

I want to open a .txt file, remove all dots from the text, and write the altered .txt as a new file.

#!python

def process_file():
    infile = open("dots.txt", "r")
    outfile = open("no_dots.txt", "w")

    for x in infile: # I'm pretty lost here.
        "." = " " # --------^
        outfile.write() # ----^
    
    infile.close()
    outfile.close()

def main():
    process_file()
    print ("Done.")

main()

Any ideas? :-/

According to your code, you are replacing all periods with spaces. If you want to replace the dots with absolutely nothing, then use two quotes side by side. ""

However, as for the script itself. Seems to me if you moved the outfile.write() outside of the loop, and changed it to outfile.write(infile), it would work.

Try that.

No dice.

I'm thinking about using string.replace or re.sub , but I'll have to do some more testing before I try to implement either.

Here is a tip:
Before the for Loop
>> readlines
Then loop into all lines using for loop
>> replace each occurrence of dot with space (or whatever you like)
>> write it to the new file
Here is completely untested code (I have no Python installed)

file1 = open('words.txt', 'r')
file2 = open('output.txt', 'w')
file1_cont = file1.readlines()
for line in file1_cont:
    line.replace('.', ' ')
    file2.write(line)

output.txt was created, but it was identical to words.txt.

My attempts so far in using re.sub have been... fruitless :icon_eek:

Steve's code is almost right :)
The problem is in line 5

line.replace('.','')

The problem with that is that it doesn't store the new string in the variable automatically, so just add a line = in front of that and it should be fine:

file1 = open('words.txt', 'r')
file2 = open('output.txt', 'w')
file1_cont = file1.readlines()
for line in file1_cont:
    line = line.replace('.', ' ')
    file2.write(line)

Hope that helps :)

output.txt was created, but it was identical to words.txt.

My attempts so far in using re.sub have been... fruitless :icon_eek:

hi,
you could do something like this:

f = open( "test.txt", "r" )
text = f.read()
f.close()

newText = ""
for each in text:
    if each == ".":
        each = "" #Or replace it with whatever you like.
    newText += each

f = open( "output.txt", "w" )
f.write( newText )
f.close()

hope this helps :)

Steve's code is almost right :)
The problem is in line 5

line.replace('.','')

The problem with that is that it doesn't store the new string in the variable automatically, so just add a line = in front of that and it should be fine:

Paul you are a genious

Steve's code is almost right :)
The problem is in line 5

line.replace('.','')

The problem with that is that it doesn't store the new string in the variable automatically, so just add a line = in front of that and it should be fine:

You are a genius Paul :)

This question has already been answered. Start a new discussion instead.