Skip to main content

🤓 Reading from Files

In this section, we'll be demonstrating different ways to read information from files.

Basic Reading

In your project directory create a text file with the name "testFile.txt" and include the following content.

testFile.txt
Howdy!
This is a test file!
You're doing great! :)

We can read and print this information using the read function as shown below. The read function by default will return all the contents of a file.

# Opening a file
myFile = open("testFile.txt", "r") # allows reading from a file

# Reading from a file
print(myFile.read())
caution

If a file with the given filename doesn't exist, an error will be thrown since you can't read from a file that doesn't exist.

You can also read a specific amount of characters by specifying a number in the read function as shown below:

# Opening a file
myFile = open("testFile.txt", "r") # allows reading from a file

# Reading 11 characters from a file
print(myFile.read(11))

Reading line by line

Using the same test file, we can manually read the file line by line using the readline function.

# Opening a file
myFile = open("testFile.txt", "r") # allows reading from a file

# Reads the first line
print("Line 1:\n", myFile.readline())

# Reads the second line
print("Line 2:\n", myFile.readline())

# Reads the third line
print("Line 13:\n", myFile.readline())

There is a much better way of doing this that is very handy for reading large files. We can use a special version of a for loop that reads a file line by line until it reaches the end.

# Opening a file
myFile = open("testFile.txt", "r") # allows reading from a file

# Reading line by line
for line in myFile:
print(line)