Gamer
Gamer

Reputation: 11

Why does my function stops reading from a file after ran through once?

My program is set up to read from a .csv file, basically a .txt file. It asks the user for a str to search for, and then searches through this file and prints out the entire line that its on. The user should be able to run the search method multiple times in a row, but it doesnt work after the first time. If it helps, a print statement when put in the search method does show that it indeed runs the second time, just nothing happens. Any ideas why this happens? Thanks.

def main():
    print("\nHello, welcome to Sales Data Menu.")
    select=0
    inFile = open("sales_data.csv", "r")
    
    while select != 4:
        select = int(input("\n1.)Search for an inovice item based on last name or id number.\n2.)Find and display the total number of items on the invoice.\n3.)Find and display the total cost of the invoice.\n4.)Exit the menu.\nEnter a number to select an option to do:  "))
        if select==1:
            search(inFile)
        else:
            print("You did not enter a valid integer. Please re-enter")
        
    inFile.close()
    
    
def search(inFile):
    item = input("Enter a last name or an id number to search by.")
    for lines in inFile:
        if item in lines:
            print(lines)

Upvotes: 0

Views: 416

Answers (3)

sal
sal

Reputation: 3593

There are few different ways to achieve what you need here. The current code will read all lines in the file, hence the file pointer (like a reading head scanning over the file) will be at the end after the first search.

Now, the thing is that file pointers do not reset automatically, that is, you must manually put it back at the beginning of the file.

The simplest way to fix your current code is to insert a file.seek(0) operation in the search() function, like this:

def main():
    print("\nHello, welcome to Sales Data Menu.")
    select=0
    inFile = open("sales_data.csv", "r")
    
    while select != 4:
        select = int(input("\n1.)Search for an inovice item based on last name or id number.\n2.)Find and display the total number of items on the invoice.\n3.)Find and display the total cost of the invoice.\n4.)Exit the menu.\nEnter a number to select an option to do:  "))
        if select==1:
            search(inFile)
        else:
            print("You did not enter a valid integer. Please re-enter")
        
    inFile.close()
    
    
def search(inFile):
    item = input("Enter a last name or an id number to search by.")
    for lines in inFile:
        if item in lines:
            print(lines)
    inFile.seek(0)  # this resets the file pointer, so the next operation will start from the beginning of the file

Upvotes: 1

jf328
jf328

Reputation: 7351

When you use the file object itself in a loop, behind the scenes python calls inFile.next() repeatedly until it reaches EOF. Looping it again doesn't reset the counter.

If you want to loop the content multiple times, you can read the whole content into memory by making it a python list of lines lines = inFile.readlines(), then you can loop over lines as many times as you want.

Upvotes: 1

Andre Ramos da Silva
Andre Ramos da Silva

Reputation: 83

https://www.tutorialspoint.com/python/file_close.htm

Python file method close() closes the opened file. A closed file cannot be read or written any more. Any operation, which requires that the file be opened will raise a ValueError after the file has been closed. Calling close() more than once is allowed.

the problem is probably on that line:

inFile.close()

Upvotes: 1

Related Questions