1

Say I have a text file like this (test.txt):

This is a 

test

my python code:

f = open("test.txt")
x = f.readlines()
s = []

for i in x:
    k = i.replace("a","not a")
    s.append(k)
    with open('output.txt', 'w') as a:
        a.write("  ".join(s))

gives the following (output.txt):

This is not a 
  
  test

but I do not want the whitespace in between. I want something like this:

This is not a test

How can I remove the newline?

testFreak
  • 19
  • 5

1 Answers1

0

Join each line immediately, then split the whole string on whitespace. Then you should have words you can loop over and replace, then join back together

replacements = {"a" : "not a"} 
def replace(s):
    if s in replacements:
        return replacements[s]
    return s

with open("test.txt") as f:
    x = " ".join(l.strip() for l in f)
x = x.split()
print(" ".join(replace(s) for s in x))
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245