Tayen Madsen Tayen Madsen - 1 year ago 77
Python Question

Code is not properly searching text file

# Obtain user input for file name, and open it
inFile = open(input("Enter file name: "), "r")
# Process data and address possible errors
countDinner = 0
countLodging = 0
countConference = 0
valueDinner = 0
valueLodging = 0
valueConference = 0
done = False
while not done :
line = inFile.readline()
try :
s = line
serviceAmount = ';'.join(s.split(';')[1:-1]) #Removes date and name regardless of format
if "dinner" in s :
countDinner = countDinner + 1
valueDinner = valueDinner + int(filter(str.isdigit, s))
print("Dinners: ", countDinner, "Value of Dinner sales: ", valueDinner)
elif "lodging" in s :
countLodging = countLodging + 1
valueLodging = valueLodging + int(filter(str.isdigit, s))
print("Lodging: ", countLodging, "Value of Lodging sales: ", valueLodging)
elif "conference" in s :
countConference = countConference + 1
valueConference = valueConference + int(filter(str.isdigit, s))
print("Conferences: ", countConference, "Value of Conference sales: ", valueConference)
elif line == "" :
done = True
else :
print("Invalid file format.")
except FileNotFoundError :
print("Unable to find file.")
finally :
done = True

Returns "Invalid file format" even when the document is set up specifically for this code. I'm not getting a syntax error, so I'm not sure whats wrong.
The document contains the text:


Answer Source

There are a lot of things you aren't doing quite right here. I tried to not only fix the issue you posted about, but also write some code that should be more clear and easier to use. I left comments to explain things.

# Don't open the file here, just get the file name. We will open in later
fname = input("Enter file name: ")

# I think using dicts is more clearn and organized. Having so many variables I think makes the code messy
counts = {"Dinner": 0,
"Lodging": 0,
"Conference": 0}

values = {"Dinner": 0,
"Lodging": 0,
"Conference": 0}

# Lets try to open the file
    with open(fname, 'r') as inFile: # Use "with", this way the file is closed automatically when we are done reading it
        for linenum, line in enumerate(inFile): # I want to enumerate each line. If there is an error on a line, we can display the line nmber this way
            line = line.lower().split(';')[1:-1] # lets make it all lower case, then split and drop as needed
            if "dinner" in line :
                counts["Dinner"] += 1 # x += 1 is the same as x = x + 1, but cleaner
                values["Dinner"] += int(line[1])
                print("Dinners: {} Value of Dinner sales: {}".format(counts["Dinner"], values["Dinner"]))
            elif "lodging" in line :
                counts["Lodging"] += 1
                values["Lodging"] += int(line[1])
                print("Lodging: {} Value of Dinner sales: {}".format(counts["Lodging"], values["Lodging"]))
            elif "conference" in line :
                counts["Conference"] += 1
                values["Conference"] += int(line[1])
                print("Conference: {} Value of Dinner sales: {}".format(counts["Conference"], values["Conference"]))
            else :
                print("Invalid file format on line {}".format(linenum)) # Here is why we used enumerate in the for loop
except FileNotFoundError: 
    print("Unable to find file.")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download