DEV Community

Cover image for Python File Operations
Baransel
Baransel

Posted on

Python File Operations

Sign up to my newsletter!.

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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Writing to File

Continue this post on my blog! Python File Operations.

Sign up to my newsletter!.

Top comments (0)