2

I have this little problem. If i create a list from the content of a txt file and print it row by row there are huge spaces between these outputs.

Like:

Name

Name

Street

Thats how i want to style it:

Name
Name
Street

And this is the code:

import os.path

print('Get User Data')
print()
vName = input('Vorname:   ')
nName = input('Nachname:  ')


data = [vName, nName]

if os.path.isfile('data/'+vName+'_'+nName+'.txt'):
    file = open('data/'+vName+'_'+nName+'.txt', 'r')
    content = file.readlines()
    for element in content:
        print(element)
else:
    data.append(input('Straße/Nr.:'))
    file = open('data/'+vName+'_'+nName+'.txt', 'w')
    for row in data:
        file.write(row)
    print()
    print('New File created. --> /data/'+vName+'_'+nName+'.txt')

file.close()

Can someone explain why this happens and how to fix it? Thank you :)

1
  • 2
    strip the strings before printing. Commented Aug 30, 2016 at 22:23

4 Answers 4

3

You simply need to strip the new line character, \n, before you print.

element.strip('\n') will get the job done.

if os.path.isfile('data/'+vName+'_'+nName+'.txt'):
    file = open('data/'+vName+'_'+nName+'.txt', 'r')
    content = file.readlines()
    for element in content:
        element = element.strip('\n') # this is the line we add to strip the newline character
        print(element)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you Harrison!
No problem! Hope I was able to help you! :)
This doesn't work. .strip() cannot modify the string. You'd need element=element.strip('\n') instead.
@viraptor Oops, forgot that strip() returns a copy of the string. Fixed that :) Thanks for pointing that out!
1

Related to this Stackoverflow question: if you don't want to alter your input, you can stop print from adding a newline.

In Python 3, the print statement has been changed into a function. In Python 3, you can instead do:

 print('.', end="")

Comments

0

When your read in the lines of the file, each contains a character at the end to skip to a new line (a newline character). When you print each of these, print also adds one, so that you now have an extra blank line between each "real" line. The solution, as @FamousJameous pointed out, is to use strip to remove the newline character from the string before printing it.

Comments

-1
for a in list(range(9)):
    print(a, file=open('file.txt', 'a'))

1 Comment

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.