2017-08-11 72 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.")