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 :)

A.Bau
  • 82
  • 1
  • 10

4 Answers4

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)
Harrison
  • 5,095
  • 7
  • 40
  • 60
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="")
Community
  • 1
  • 1
Alan
  • 2,914
  • 2
  • 14
  • 26
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.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
-1
for a in list(range(9)):
    print(a, file=open('file.txt', 'a'))
vadim vaduxa
  • 221
  • 6
  • 16
  • 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. – Brian Tompsett - 汤莱恩 Aug 31 '16 at 09:47