Below is the code to a part of a program. This part prints the line the user enters (same as idnum). It retrieves the data from all the 6 files fine, however when it prints them there is line separating each piece of data. 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.
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. To read it without the \\n
character, follow the advice of this question and use read().splitlines()
instead:
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.")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.