问题
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:
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)
回答2:
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="")
回答3:
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.
回答4:
for a in list(range(9)):
print(a, file=open('file.txt', 'a'))
来源:https://stackoverflow.com/questions/39237963/python-too-much-space-between-printing-lines-read-from-a-text-file