9-2. Reading a File in Python

Reading files is a common operation in many programming tasks. Below is the basic way to read the contents of a file in Python, with some additional best practices.

Basic File Reading

Here's a simple example of how to open a file for reading and print its contents:

# Open a file for reading
f = open("demofile.txt", "r")
print(f.read())
f.close()

 

Explanation:

  • Open the File: The open function is used to open the file "demofile.txt" in read mode ("r"). You need to ensure that the file "demofile.txt" must be located in the same folder where this script is run.
  • Read the Contents: The read method reads the entire content of the file.
  • Print the Contents: The print function prints the content to the console.
  • Close the File: The close method closes the file, which is important to free up system resources.

Best Practices

Using the with statement is recommended for handling files because it ensures that the file is properly closed even if an error occurs during the file operation. Here's how you can do it:

# Open a file for reading using the 'with' statement
with open("demofile.txt", "r") as f:
    content = f.read()
    print(content)
# No need to explicitly close the file

Reading a File Line by Line

If you want to read multiple lines, you can call readline() multiple times or use a loop. Here’s an example using a loop:

# Open a file for reading
with open("demofile.txt", "r") as f:

    # Read and print lines one by one
    while True:
        line = f.readline()
        if not line: # End of file
            break
    print(line.strip()) # Strip newline characters

 

Explanation:

  • Using with Statement: Ensures the file is properly closed after its suite finishes.
  • Loop through Lines: Use a while loop to read each line until the end of the file.
  • Check for End of File: readline() returns an empty string when the end of the file is reached.
  • Print Each Line: print(line.strip()) prints the line, removing any leading or trailing whitespace including newline characters.

Or you can read the file line by line using the file object directly. Here’s an example:

# Open a file for reading line by line
with open("demofile.txt", "r") as f:
    for line in f:
        print(line.strip())

 

Explanation:

  • Using with Statement: Ensures the file is properly closed after its suite finishes, even if an exception is raised.
  • Reading Line by Line: The for loop reads the file line by line.
  • Strip Whitespace: strip() removes any leading and trailing whitespace, including the newline character at the end of each line.

Reading All Lines into a List

If you need to read all lines at once and store them in a list, you can use the readlines() method:

# Open a file for reading
with open("demofile.txt", "r") as f:
    lines = f.readlines()

    # Print each line from the list
    for line in lines:
        print(line.strip())

 

Explanation:

  • Read All Lines: readlines() reads all the lines in the file and returns them as a list.
  • Iterate Through List: Use a for loop to iterate through the list and process each line.