D
D
Dmitry2016-04-15 13:26:34
Python
Dmitry, 2016-04-15 13:26:34

How to get rid of empty lines in file.write()?

Essence of the question. There is a tuple of strings, each line of which starts with characters \r\n.
When outputting a tuple to the console:

for x in tuple:
    print(x.decode('cp1251'))

line breaks are displayed correctly:
1. one;
2. two;
3. three;

When writing lines to a file:
file = open('file.txt', 'a')
for x in tuple:
    file.write(x.decode('cp1251'))

after each line, another carriage return appears:
1. one;

2. two;

3. three;

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2016-04-15
@kashamalasha

The problem was the carriage return character "\r".
Decided like this:

for x in tuple:
    file.write(x.decode('cp1251').replace('\r\n', '\n'))

V
Vladimir Kuts, 2016-04-15
@fox_12

file.write(x.decode('cp1251').strip()+'\n')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question