gpt4 book ai didi

python - 从文件中检索数据

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:25 28 4
gpt4 key购买 nike

下面是部分程序的代码。这部分打印用户输入的行(与 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(默认可能是'\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.")

关于python - 从文件中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45632363/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com