First, we have a problem that we constantly experience while doing file operations. When we try to read the file or save the file, we get errors such as where we saved the file and when trying to open the file, the file could not be reached, the file does not exist. For this reason, we first do the operations related to the file, etc. Let’s find out the directory we made. That’s why Python provides us with a library. This library is the os
library. Let’s add the library immediately and learn the file extension, we use the getcwd()
function for this.
import os
print(os.getcwd())
# /Users/baran/Documents/work/baransel.dev
We have learned the directory where the file will be created. Secondly, there is one more thing we need to learn. There are some modes according to the operation we will do on the file. With these modes, we need to specify the operations we will do on the file. These modes are;
Mode | Description |
---|---|
r | It just opens a file for reading. File pointer to the beginning of the file is placed. This is the default mode. |
r+ | Opens a file for both reading and writing. The file pointer is placed at the beginning of the file. |
w | It just opens a file for writing. If the file exists, overwrites the file. If the file does not exist, it creates a new file to write to. |
w+ | Opens a file for writing and reading. If the file exists overwrites the existing file. If the file does not exist, read and Creates a new file for writing. |
a | Opens a file for attachment. file pointer if the file exists, it is at the end of the file. That is, it is in file attach mode. To write if the file does not exist creates a new file. |
a+ | Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in attach mode. If the file does not exist, creates a new file for reading and writing. |
Now that we have learned the basic file modes, let’s open our first file. The function that allows us to open a file is the open()
function and consists of two parameters. If the first parameter is the name
of the file, the second parameter is the mode
of the file, what will you do on this file, will you just read, write something to the file or add something new to the file, I have already given these modes above.
Example:
open('file.txt','mode')
Writing to File
We just gave general information, now let’s open our file and add something.
Let’s show the function that allows us to write to the file.
file = open("example.txt","w")
file.write("Hello world! :)")
file.close()
Now let’s go to /Users/baran/Documents/work/baransel.dev
and you can see our file has been created.
As you can see, we created our example.txt
file and added some text to it. By the way, there is something we need to pay attention to, we closed our close()
file at the end, and we have to do this every time.
Close file automatically
Now you’re going to say do I have to deal with it every time, isn’t there another way? Of course, Python has found a solution for that too. Let me just show you with the previous application.
with open("example.txt","w") as file:
file.write("Hello world! :)")
I recommend using this method.
Now I want to give you a very important information. Python saves everything written to the file as a string
. Now let’s try to save a data type other than character string
, for example, let’s see the list
and see what happens.
with open("example.txt","w") as file:
file.write(["Hello world\n","Welcome to Python lessons"])
# File "/Users/baran/Documents/work/baransel.dev/file.py", line 2, in <module>
# file.write(["Hello world","Welcome to python lessons"])
# TypeError: write() argument must be str, not list
As you can see, the Python interpreter tells us that we can only save strings
with the write()
function, but not lists
. We will use another function for this, which is the writelines()
function. Let’s use it now.
with open("example.txt","w") as file:
file.write(["Hello world\n","Welcome to Python lessons"])
When you run the code, no errors occur, and we have successfully saved the information to the file. There is also something else we should pay attention to. All data is written on the same line in .txt
files. We use the \n
operator to write it on the bottom line. Every time we run the code, Python overwrites that file each time and the old information is deleted. If you do not want the information to be deleted, if you want to add new information, you must open the file in a
mode.
File Reading
We’ve just done the writing to the file, now let’s read the file we wrote, we use the read()
function for this. Let’s do it now;
with open("example.txt","r") as file:
print(file.read())
# Hello world
# Welcome to Python lessons
There is something we need to pay attention to here, when we open the file in w
mode, if the file does not exist, a new file is created. But when we try to open it in r
mode. It will give an error like this.
FileNotFoundError: [Errno 2] No such file or directory: "example.txt"
So the file not found error. For this, we need to check whether our file exists before opening the file. Let’s do this right away with isfile()
, if there is a file, let’s read the file, if there is no file, it will give an output as file not found.
import os
if os.path.isfile("example.txt"):
with open("example.txt","r") as file:
print(file.read())
else:
print("File not found")
In this way, we checked whether the file exists or not with the isfile()
function. Also, if you’re only going to read. We don’t need to specify in which mode to open the file. Because Python opens in reading mode by default.
readlines()
function, what does this function do? This function assigns the file to a list while reading the file. It also reads each line of the file as if it were an element of the list. Let’s use it right away, let’s have a file like this.
import os
if os.path.isfile("example.txt"):
with open("example.txt", "r") as file:
print(file.readlines())
else:
print("File not found")
We get an output like this:
['Python\n', 'HTML\n', 'PHP\n', 'Kotlin\n', 'Swift']
So what if we want to read only a part of the reading process in the file, we can use the readline()
function in it. With this function we can read only one line.
import os
if os.path.isfile("example.txt"):
with open("example.txt", "r") as file:
print(file.readline())
else:
print("File not found")
# Python
As you can see, it read a single line, so can we read from anywhere, of course we can. We will use a function for this, which is the seek()
function. So what does the function do? When Python reads files, it moves the cursor to where it is read. Therefore, we can move the cursor to the place we want and read from that part. Let’s do it now, move the cursor to the 10th character, let’s read after that part.
import os
if os.path.isfile("example.txt"):
with open("example.txt") as file:
file.seek(10)
print(file.read())
else:
print("File not found")
We get an output like this:
ML
PHP
Kotlin
Swift
We got an output as python read after the 10th character. That’s why it didn’t read the first 9 characters. If you want to know where the cursor is, then you can use the tell()
function.
Likewise, we can make the desired change by moving the cursor to the beginning, end or middle of the file with this function.
File deletion
In order to delete the file, we will use the os
library, which is a library we used before, for this we use the remove()
function.
import os
os.remove("example.txt")
In this way, we will delete a file. If we want to delete a folder, then we will use the rmdir()
function.
import os
os.rmdir('baransel.dev')
In this way we will have deleted an entire folder.
File Methods
name
The method that gives the name of the file.
with open("example.txt") as file:
file.read()
print("Filename: ", file.name)
# Filename: example.txt
mode
The method that gives you which mode the file is in.
with open("example.txt", "r") as file:
file.read()
print("File mode: ", file.mode)
# File mode: r
closed
Checks if the file is closed.
with open("example.txt", "r") as file:
file.read()
print("File closed: ", file.closed)
# File closed: True
writable
Checks if the file is in write mode and open mode. Returns True
or False
.
file = open("example.txt","r")
file.readline()
print(file.writable())
# False
readable
Checks if the file is in read mode. Returns True
or False
.
file = open("example.txt","r")
file.readline()
print(file.readable())
# True