2025faCSE160/bigos/lecture20251104/fileio_census/get-firstname.py

38 lines
972 B
Python

#!/usr/bin/python3
## ============================ One time initializations ========================
fileName = "female-first.txt"
nameToSearch = input("Enter a first name: ")
nameToSearch = nameToSearch.upper()
## ============================ Open and process file(s) ========================
try:
inFile = open(fileName,'r')
count = 1
runFlag = True
while(1): # Process while true
line = inFile.readline()
if line == "": # Exit on empty line == end of file
break
line = line.rstrip("\n")
# print(count,line)
fieldList = line.split(" ")
# print(fieldList)
print(fieldList[0],len(fieldList[0]))
if nameToSearch == fieldList[0] :
print("Matched {} = {} at position {}".format(nameToSearch,fieldList[0],count))
break
count = count + 1
except:
print("Some error occurred. Ending here")
exit(-1)
inFile.close()