DEV Community

Cover image for Handling Files in Python 🐍
KetanIP
KetanIP

Posted on • Originally published at ketaniralepatil.com

Handling Files in Python 🐍

This post was originally posted here, you can eat the complete post here.

File handling is one of the most important part of a programmer's life let him/her be a data scientist, web developer or even a cyber security expert. So I have decided to write this post all about handling files in python.

To open files and bring them in python we have the following syntax,

file = `open(file_name, mode)`
Enter fullscreen mode Exit fullscreen mode

To open a file in read mode we use the following syntax, . The first argument is obviously the file_name and the second one is a bit more interesting in it is the mode in which you want to open the file and it determines whether we can read,append, write , open in binary and so on we will see it down.

For the entirety of this blog post we are going to assume that our python file and our text file which we will be using to perform operations upon are located in the same folder, and the content of the text file is as follows, I have not written it just copied it from a random text generator online as I don't like lorem ipsum that much.

readme.txt

He found himself holding onto the worst type. 
It was the type of secret that could gnaw away at your insides if you didn't tell someone about it, but it could end up getting you killed if you did.
Enter fullscreen mode Exit fullscreen mode

Reading Files

Reading files in python is damn simple, let's understand it by an example, in this example we will be reading our text file readme.txt` and is located in the same folder as our python files is located.

To open file in read mode we pass 'r' place of mode in the open file syntax, to read the the file don't worry about these modes I will provide a list at the end of the post with all of the them along with their functions.

main.py

file = open('readme.txt', 'r')

if file.mode == 'r':
    fileContent = file.read()
    print(fileContent)
Enter fullscreen mode Exit fullscreen mode

In above code we are opening a file in read mode and then checking whether it is open in read mode and if it is then we are reading the content of file by using .read() method in it and then printing it.


Sorry to interrupt you but I want to tell you one thing that I have started a small blog you may continue reading it here it will help me a lot.

Top comments (1)

Collapse
 
fabiocaccamo profile image
Fabio Caccamo • Edited

I suggest you to try the python-fsutil library.