简体   繁体   English

从文件中检索数据

[英]Retrieving data from files

Below is the code to a part of a program. 下面是程序一部分的代码。 This part prints the line the user enters (same as idnum). 此部分打印用户输入的行(与idnum相同)。 It retrieves the data from all the 6 files fine, however when it prints them there is line separating each piece of data. 它可以很好地从所有6个文件中检索数据,但是在打印它们时,每行数据之间存在一行分隔线。 What do I need to do to make the program print the data without line spacing. 我需要做些什么才能使程序打印没有行距的数据。

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.")

You can specify end in print function(default might be '\\n'. I also compacted your code. 您可以指定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.")

Your readlines() is picking up the newline character from the file. 您的readlines()正在从文件中拾取换行符。 To read it without the \\n character, follow the advice of this question and use read().splitlines() instead: 要读取不带\\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