Python:从文本文件读取的打印行之间的空间太大 [英] Python: Too much space between printing lines read from a text file

查看:68
本文介绍了Python:从文本文件读取的打印行之间的空间太大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个小问题.如果我从txt文件的内容创建列表并逐行打印,则这些输出之间会有很大的空白.

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.

赞:

名称

名称

街道

那是我想要的样式:

名称
名称
街道

Name
Name
Street

这是代码:

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

推荐答案

在打印之前,您只需要剥离换行符 \ n .

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

element.strip('\ n')将完​​成工作.

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)

这篇关于Python:从文本文件读取的打印行之间的空间太大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆