2017-08-11 68 views
1

下面是程序一部分的代码。这部分打印用户输入的行(与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.") 
+1

你也可以使用'打印(line.rst rip('\ n'))' – coder

回答

2

您可以指定打印功能end(默认情况下可能是“\ 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.") 
+0

谢谢你这个工作,但所有的地方,除了姓氏缩进,所以我改变了结束=''结束=''。知道它的工作原理就是我想要的。 – user8435959

2

readlines()从文件拿起换行符。阅读它没有\n性格,遵循this question的建议,使用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.")