Readline() 在输出中给我空白 space
Readline() is giving me blank space in output
我是 Python 的初学者,我正在尝试创建一个没有库的具有添加和搜索功能的数据库。一切都很好,除了当编译器看到这个词在文本文件中并且我告诉它 readline() 时,它给了我一个空白 space。这是我的代码:
data = open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "a+")
x = input ("Would you like to add or search?")
if x == "Add".lower():
data.write(input("Please enter: (Name,Age,Address,Date of birth,blood type,type(doctor,nurse,patient),disease,Married(yes or no)"))
data.write('\n')
def search():
if x == "Search".lower():
y = input ("What would you like to search for? (Name,age,type)")
if y == "Name".lower():
z = input("Who would you like to search for?")
with open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "r") as f:
if z in f.read():
print(f.readline())
search()
如果有人能告诉我如何修复它,我将不胜感激。提前致谢!
你可以这样做:
with open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "r") as f:
for line in f:
if z in line:
print(line)
请注意它会打印出所有匹配的行。如果您只想打印第一次出现,您可以在找到匹配项时中断 for 循环:
with open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "r") as f:
for line in f:
if z in line:
print(line)
break
我是 Python 的初学者,我正在尝试创建一个没有库的具有添加和搜索功能的数据库。一切都很好,除了当编译器看到这个词在文本文件中并且我告诉它 readline() 时,它给了我一个空白 space。这是我的代码:
data = open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "a+")
x = input ("Would you like to add or search?")
if x == "Add".lower():
data.write(input("Please enter: (Name,Age,Address,Date of birth,blood type,type(doctor,nurse,patient),disease,Married(yes or no)"))
data.write('\n')
def search():
if x == "Search".lower():
y = input ("What would you like to search for? (Name,age,type)")
if y == "Name".lower():
z = input("Who would you like to search for?")
with open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "r") as f:
if z in f.read():
print(f.readline())
search()
如果有人能告诉我如何修复它,我将不胜感激。提前致谢!
你可以这样做:
with open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "r") as f:
for line in f:
if z in line:
print(line)
请注意它会打印出所有匹配的行。如果您只想打印第一次出现,您可以在找到匹配项时中断 for 循环:
with open("C:\Users\PC\Desktop\Python Course\Course\Advanced Python\Exam\data.txt", "r") as f:
for line in f:
if z in line:
print(line)
break