Python has a concept of File Handline, which is an important concepts in every programming languages. It allows to read, write, append and create a file. Its not a good practice to store every data in a variable. The value stored in the variables maybe gone while building a big projects as there is a chance of getting overridden or removal. To remove such problem, this is where file handling come in place.
In this post, we are going to see simple example of file handling. We will be using python default in-built function to read the content of the file. I have a sample text file where I have written some text. And my python file is in the same directory where that text file is. So make sure, you also do the same.
f = open("Sample Text.txt", "r") print(f.read()) f.close()
open() function takes in two parameter, the name of the file itself and the mode with which you want to handle. Right now, we are focusing on read mode. Running this code will give the following output.
To read only the first line, you can use
readline(). See in the picture below:
To print another line, you can use the same print() function two times and so on. To read only certain parts of the file you can specify how much characters you want to use. For example:
print(f.read(15)). If you use this, the output will be as below:
Always remember to close your file. Otherwise, while working on big projects, if file is not closed, then there is a chance that it will be tampered, leaked or destroyed.