繁体   English   中英

从文件中检索数据

[英]Retrieving data from files

下面是程序一部分的代码。 此部分打印用户输入的行(与idnum相同)。 它可以很好地从所有6个文件中检索数据,但是在打印它们时,每行数据之间存在一行分隔线。 我需要做些什么才能使程序打印没有行距的数据。

1 smith

1 john

1 02/01/1234

1 4 pigeon street

1 123456765432234432

1 male

idnum= int(input("Enter id number: "))

def display():
    line = open("Surname", "r").readlines()[idnum-1]
    print (line)
    line = open("Forename", "r").readlines()[idnum-1]
    print (line)
    line = open("Date of birth", "r").readlines()[idnum-1]
    print (line)
    line = open("Home address", "r").readlines()[idnum-1]
    print (line)
    line = open("Home phone number", "r").readlines()[idnum-1]
    print (line)
    line = open("Gender", "r").readlines()[idnum-1]
    print (line)



import os.path
if os.path.exists("Surname"):
    display()
else:
    print("No data exists.")

您可以指定end in print功能(默认值可能是'\\ n'。我也压缩了您的代码。

from os import path

idnum= int(input("Enter id number: "))

def display():
    for file in ["Surname", "Forename", "Date of birth", "Home address", "Home phone number", "Gender"]:
        with open(file) as f:
            print(f.readlines()[idnum-1], end=' ')

if os.path.exists("Surname"):
    display()
else:
    print("No data exists.")

您的readlines()正在从文件中拾取换行符。 要读取不带\\n字符的内容,请遵循此问题的建议,并改用read().splitlines()

import os

idnum= int(input("Enter id number: "))

def display():
    for file in ["Surname", "Forename", "Date of birth", "Home address", "Home phone number", "Gender"]:
        with open(file) as f:
            print(f.read().splitlines()[idnum-1])

if os.path.exists("Surname"):
    display()
else:
    print("No data exists.")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM