Opening and Reading Files in Python: A Step-by-Step Guide
Learn the essentials of opening and reading files in Python. This guide covers how to access files located in various directories and read their contents. Explore practical examples, including how to work with files located in the same folder as your Python script.
Python File Open
Opening and reading files is a fundamental task in Python. Here, we will explore how to open a file, read its contents, and handle files located in different directories.
Open a File on the Server
Assume we have the following file, located in the same folder as our Python script:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open()
function. This function returns a file object, which has a read()
method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
Opening a File in a Different Location
If the file is located in a different location, you will need to specify the file path, like this:
Example
f = open("D:\\myfiles\\welcome.txt", "r")
print(f.read())
Read Only Parts of the File
By default, the read()
method returns the whole text, but you can also specify how many characters you want to return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
You can return one line by using the readline()
method:
Example
f = open("demofile.txt", "r")
print(f.readline())
By calling readline()
twice, you can read the first two lines of the file:
Example
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files
It is good practice to always close the file when you are done with it:
Example
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: Always close your files. In some cases, due to buffering, changes made to a file may not show until you close the file.