Python allows you to work with the file system, which includes both files and directories. Using the built-in system functions, you can access, manipulate, open, read, write, append, and close files.
Opening a File
To open a file, use the open function. The first parameter is the path to the file, with the second being the mode.
Here is the list of modes:
r: Opens a file for reading.
a: Opens a file for appending.
w: Opens a file for writing.
x: Creates a new file.
Let's use the first one to open a file:
PYTHON
file = open("file.txt", "r")
That's pretty much it. As long as the file exists, you have successfully opened a file in Python!
Reading a File
Now that you've opened a file, let's read from it. Use the read() function on the file:
PYTHON
file = open("file.txt", "r")
print(file.read())
Assuming the file contained this text:
HTML
Hello!
Welcome to sabe.io!
Have fun!
That is exactly what you would see when you try to print it out. If you want to limit the number of characters returned back, give the length as the parameter, like so:
PYTHON
file = open("file.txt", "r")
print(file.read(6))
BASH
Hello!
Read File Line by Line
Maybe instead of getting the entire file, you want to read it line by line. Thankfully, there is already a built-in function for this. The readline() function reads a file line by line each time. If you use it twice, the second time will return the second line.