***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***
***Use tabs for Content***

POSTS

    Using Loops to Process Files

    When a program uses a file to write or read a large amount of data, a loop is typically involved. Quite often a program must read the contents of a file without knowing the number of items that are stored in the file.

    In Python, the readline method returns an empty string (' ') when it has attempted to read beyond the end of a file. This makes it possible to write a while loop that determines when the end of a file has been reached.

    Here is the general algorithm, in pseudocode:

    Open the file

    Use readline to read the first line from the file

    While the value returned from readline is not an empty string:

    Process the item that was just read from the file

    Use readline to read the next line from the file.

    Close the file


    Using Python’s for Loop to Read Lines

    The Python language also allows you to write a for loop that automatically reads line in a file without testing for any special condition that signals the end of the file.

    Here is the general format of the loop:

    for variable in file_object:

    statement

    statement

    etc.

    In the general format, variable is the name of a variable and file_object is a variable that references a file object. The loop will iterate once for each line in the file.

    Example:

    # This program uses the for loop to read

    # all of the values in the sales.txt file.

    def main():

    # Open the sales.txt file for reading.

    sales_file = open('sales.txt', 'r')

    # Read all the lines from the file.

    for line in sales_file:

                            # Convert line to a float.

    amount = float(line)

    # Format and display the amount.

    print(format(amount, '.2f'))

     # Close the file.

    sales_file.close()

     # Call the main function.

    main()