[英]Search a data.txt file for information based on user input and print it(Python 3.5.1)
下面的代码读取data.txt文件并在data.txt文件中打印记录。
text_file = open("data.txt", "r")
lines = text_file.readlines()
print (lines)
print (lines)
text_file.close()
def print_all_records(records):
print("Date" + "\t\t" + "Branch" + "\t\t" + "Daily Sale" + "\t\t" + "Transactions")
for record in records:
parts = record.split(",")
print(parts[0] + "\t" + parts[1] + "\t" + "$" + parts[2] + "\t\t" + parts[3])
data.txt文件中的信息示例
1-2-2014,Frankton,42305.67,23
12-4-2014,Glenview,21922.22,17
10-2-2015,Glenview,63277.9,32
我如何做到这一点,以便我可以按日期查询记录。 例如,如果用户输入日期1 2 2014,它将搜索data.txt文件以查找该日期是否存在,然后打印该行记录。 如果找不到任何内容,它将要求用户一次又一次尝试,直到找到与记录匹配的日期为止。
我假设您使用的是Python 3。
def print_entries(date):
"""Prints all the entries that match with date"""
with open('a.txt', 'r') as f:
flag = False
content = f.readlines()
content = [line.strip('\n').split(',') for line in content]
for row in content:
if row[0] == date:
flag = True
print(*row, sep='\t')
if not flag:
print('Try again')
return flag
while not print_entries(input("Enter date :")):
pass
如果您使用的是Python 2,则将print(*row, sep = '\\t')
替换为print('\\t'.join(row))
。
运行程序-
Enter date :12-4-2014
12-4-2014 Glenview 21922.22 17
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.