PYTHON PROGRAMMING EXERCISES 3: FILE HANDLING

in STEMGeeks2 months ago

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()

The 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.

image.png

To read only the first line, you can use readline(). See in the picture below:

image.png

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:

image.png

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.

Sort:  

Which one is more complex between phyton and java

It depends on how well you can grasp the concepts. I studied java too. I could get every concepts of it but as I learned I knew that I had to learn so many things like servlets, JSP and so much more. So, I give up Java and learned Python. Its beginner friendly and easier to learn than Java.

Ohh. I see so let me go into python then