DEV Community

Cover image for Introduction to Python Programming Basics(Part 4)
Billy Okeyo
Billy Okeyo

Posted on

Introduction to Python Programming Basics(Part 4)

File Management

Python has different methods you can do to a file which include;

Creating a file
Reading a file
Updating a file
Deleting a file

In order to work with any file in python we have to first open it.

file = open('file.txt', 'w')
Enter fullscreen mode Exit fullscreen mode

The above code will open the file and if the file is not found, it will create the file.
Now that we have a file opened, we can try to get some info about the file.
Note: we used w so as to open the file in write mode.

file = open('file.txt', 'w')
print("Name of File: ", file.name)
print("Mode Opened In: ", file.mode)
Enter fullscreen mode Exit fullscreen mode

When the above code is run, it will output:

Name of File: file.txt
Mode Opened In: w
Enter fullscreen mode Exit fullscreen mode

Now let's try writing something into our file:

file = open('file.txt', 'w')
file.write("I am learning Python ")
file.write("Learning Python is Fun")
file.close()
Enter fullscreen mode Exit fullscreen mode

It's always a good practice once you finish working with a file you close that's why I have used file.close()
For you to see the change you have to open the file.txt to see whatever you wrote has been executed.
Now that we have written something in our file, let's try appending to it.
Appending basically is adding some values to an existing one or a file without deleting the current values in the file. So to append we use the mode a which is used for appending

file = open('file.txt', 'a')
file.write(" and it is easy")
file.close()
Enter fullscreen mode Exit fullscreen mode

Now to read what we have in our file. We use the r+ mode.
And in reading we create a variable and then assign whatever has been read from the file to the variable we created then it is the variable we now call to be printed.

file = open('file.txt', 'r+')
contents = file.read(200)
print(contents)
Enter fullscreen mode Exit fullscreen mode

I have used 200 so as it reads the first 200 characters of our text file. Now with that we will get the text file contents right in our terminal as follows

I am learning Python Learning Python is Fun and it is easy
Enter fullscreen mode Exit fullscreen mode

Hope you are progressing well, that's all for today, see you later.

Top comments (0)