Krish
Krish

Reputation: 1081

Python: .strip() and .write() seem to produce whitespace

I wrote some code to let me type special characters without learning the commands for them so I wrote this:

file = open('test.txt', 'r+')
text = file.read()

text = text.replace('//a', 'Ä')
text = text.replace('//o', 'Ö')
text = text.replace('//u', 'Ü')

text = text.replace('/a', 'ä')
text = text.replace('/o', 'ö')
text = text.replace('/u', 'ü')

text = text.replace('/s', 'ß')

file.truncate(0) # Clears the file
file.write(text.strip()) # edit was .strip(''), made no diffence 
print(text)

An example input would be 'n/achtes' which would become 'nächtes' This sort of works but when I run the file I get a huge amount of blank space in the text file for example 'n/achtes' turns into:

 '        nächtes'

If I run the program a second time the output, on sublimetext 3, ends with nächtes but has 8 uncopyable copies of <0x00> in a different colour. The amount of blank spaces increases as well in the text file.

Upvotes: 2

Views: 107

Answers (2)

Ralf
Ralf

Reputation: 16505

You could try to open the file twice, once for reading and once for writing.

filename = 'text.txt'

with open(filename, 'r') as f:
    text = f.read()
print('-' * 20)
print('old text:')
print(text)

replacement_list = [
    ('//a', 'Ä'),
    ('//o', 'Ö'),
    ('//u', 'Ü'),
    ('/a', 'ä'),
    ('/o', 'ö'),
    ('/u', 'ü'),
    ('/s', 'ß'),
]
for s_old, s_new in replacement_list:
    text = text.replace(s_old, s_new)
print('-' * 20)
print('new text:')
print(text)

with open(filename, 'w') as f:
    f.write(text.strip())

Upvotes: 0

nosklo
nosklo

Reputation: 222862

truncate(0) resizes the file to zero size, but the current position is not changed.

When writing the data, it is written at current position, so the rest of the file gets null bytes to "pad".

It is a better practice to use truncate() without parameter to truncate the file in the current position:

f.seek(0)    # go to the beginning of the file
f.truncate() # truncate in current position

Upvotes: 3

Related Questions