[英]Error parsing text file - Python
我有一個文本文件,其名稱字段與數字關聯。 字段由空白行分隔。 該代碼應提供選定的名稱及其相關字段。 這是我的堆棧跟蹤:
1,Hospital_Records
2,Exit
Enter your choice: 1
Enter your first and last name: John Wilson
Name: John Wilson
Days in Hospital: 3
Daily Rate: 400.0
Service Charges: 1000.0
medication_Charges: 5987.22
Total Charges: 8187.22
Traceback (most recent call last):
File "E:/test_file_parse.py", line 63, in <module>
main()
File "E:/test_file_parse.py", line 29, in main
days_in_hospital = int(file.readline())
ValueError: invalid literal for int() with base 10: '\n'
我正在提供我的代碼和文本文件:
def main():
#create a bool variable to use as a flag
found = False
searchName=''
days_in_hospital=0
daily_rate=0.0
service_charge= 0.0
medication_charges= 0.0
choice=0
total_charges= 0.0
while choice!=2:
print("1,Hospital_Records")
print("2,Exit")
choice= int(input("Enter your choice: "))
if choice==1:
#Get the search value
searchName= input("Enter your first and last name: ")
file= open("c:\\Python34\HospitalRecords.txt", "r")
#Read the first record's name field
record = file.readline()
#Read the rest of the file
while record!='':
days_in_hospital = int(file.readline())
daily_rate = float(file.readline())
service_charge = float(file.readline())
medication_charges = float(file.readline())
total_charges = ((days_in_hospital * daily_rate) +
service_charge + medication_charges)
#strip the newline character from the record
record= record.rstrip('\n')
#determine if this record matches the search value
if record==searchName:
print("Name: " ,searchName)
print("Days in Hospital: " , days_in_hospital)
print("Daily Rate: " , daily_rate)
print("Service Charges: " , service_charge)
print("medication_Charges: " , medication_charges)
print("Total Charges: " ,total_charges)
print()
#set the found flag to True
found = True
elif choice==2:
print("You are successfully exited your program")
else:
print("Invalid entry")
#If the search value was not found in the file
#display a message
if not found:
print("That name was not found in the file.")
file.close()
主要()
這是文本文件:
John Wilson
3
400.00
1000.00
5987.22
Charles Sanders
10
12000.34
2487.77
8040.66
Susan Sarandon
1
300.22
8463.88
12777.33
Mary Muffet
8
4976.55
4050.00
15839.20
另外,如果我輸入的名字不是約翰·威爾遜(John Wilson),則出現以下錯誤:
1,Hospital_Records
2,Exit
Enter your choice: 1
Enter your first and last name: Susan Sarandon
Traceback (most recent call last):
File "E:/test_file_parse.py", line 63, in <module>
main()
File "E:/test_file_parse.py", line 29, in main
days_in_hospital = int(file.readline())
ValueError: invalid literal for int() with base 10: '\n'
您的代碼中存在邏輯錯誤,導致無法與用戶順利進行交互。 (例如,您對記錄名稱的處理,記錄之間的空白行,文件關閉的時間,等等。)我重新設計了您的邏輯,看看是否能為您提供所需的結果:
FILE_NAME = r"c:\\Python34\HospitalRecords.txt"
def main():
choice = 0
while choice != 2:
print("1) Hospital_Records")
print("2) Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
# create a bool variable to use as a flag
found = False
# Get the search value
searchName = input("Enter your first and last name: ")
file = open(FILE_NAME)
# Read the first record's name field
record_name = file.readline().rstrip('\n')
# Read the rest of the file
while record_name != '':
days_in_hospital = int(file.readline())
daily_rate = float(file.readline())
service_charge = float(file.readline())
medication_charges = float(file.readline())
# determine if this record matches the search value
if record_name == searchName:
print("Name: ", searchName)
print("Days in Hospital: ", days_in_hospital)
print("Daily Rate: ", daily_rate)
print("Service Charges: ", service_charge)
print("medication_Charges: ", medication_charges)
total_charges = ((days_in_hospital * daily_rate) + service_charge + medication_charges)
print("Total Charges: ", total_charges)
print()
# set the found flag to True
found = True
break
record_separator = file.readline()
# strip the newline character from the record
record_name = file.readline().rstrip('\n')
file.close()
if not found:
# If the search value was not found in the file
# display a message
print("That name was not found in the file.")
elif choice == 2:
print("You successfully exited the program.")
else:
print("Invalid entry!")
main()
您正在逐行讀取文件,並且代碼假定的格式與實際文件不匹配。
您的第一個readline()會抓住文件的第一行(“ John Wilson”),然后在循環中再執行4個readline()來獲取下一行的所有數字。
此時,下一個readline()將占據文件的第6行(空白行“ \\ n”)。 不過這還沒有發生。 假定第一個記錄與您的搜索不匹配,就像在錯誤情況下一樣。 您的代碼執行的下一個readline()是:
days_in_hospital = int(file.readline())
並嘗試從空行中生成整數時引發錯誤。 因此,您需要在循環中添加一個readline()來跳過該空白行。
第二個問題是,在循環再次開始之前,您的變量“ record”實際上並未移至下一行。 第二次執行while循環時,記錄仍然等於“ John Wilson”。
因此,您可以執行以下操作:
#determine if this record matches the search value
if record==searchName:
print("Name: " ,searchName)
print("Days in Hospital: " , days_in_hospital)
print("Daily Rate: " , daily_rate)
print("Service Charges: " , service_charge)
print("medication_Charges: " , medication_charges)
print("Total Charges: " ,total_charges)
print()
#set the found flag to True
found = True
else:
file.readline() #skip the blank line
record = file.readline() #read the next record
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.