As we now have an idea of what files(text or binary) are and their access modes, we are now ready to dive into the discussion of file handling methods. When we want to read or write a file (say on our hard drive), we must first open the file. When we open a file, we are asking the operating system to find the file by name, making sure the file exists.
Python has a built-in open() function to open a file.
The syntax of the function is:
open("filename" ,"mode")
To open a file, we must specify two things,
For Example,
open("myfile.txt")
The file “myfile.txt” will open in "rt" mode as it is the default mode. But the best practice is to follow the syntax to avoid errors.
The open function returns a file object. We store this file object into a variable which is generally called as a file pointer/file handler. Here is a code snippet to open the file using file handing in Python,
f=open("myfile.txt," "w")
You can use this file pointer to further add modifications in the file. An error could also be raised if the operation fails while opening the file. It could be due to various reasons like trying to access a file that is already closed or trying to read a file open in write mode.
f = open("myfile.txt", "r")
f.read(2); #Here, you will get the first two characters of the file.
f=open("myfile.txt","r");
f.readlines() #Returns a list object
Note: The default mode to read data is text mode. If you want to read data in binary format, use ''rb".
Is it necessary to close a file?
The answer is yes, it is always the best practice to close a file after you are done performing operations on it. However, Python runs a garbage collector to clean up the unused objects, but as good programmers, we must not rely on it to close the file. Python has a build-in close() function to close a file i.e;
f.close()
I hope you like this tutorial. Here, we have discussed different file handling in Python with examples that will help you while working on real-world projects.
f = open("harry.txt", "rt")
print(f.readlines())
# print(f.readline())
# print(f.readline())
# print(f.readline())
# content = f.read()
#
# for line in f:
# print(line, end="")
# print(content)
# content = f.read(34455)
# print("1", content)
#
# content = f.read(34455)
# print("2", content)
f.close()
Thanks, Harry Bhai for Awesome Tutorials |:::::::::::::::::| Full Notes and Source Code :::::::::::::::::::::::::::::::::::::::} https://github.com/Optimized-World/Complete-Python-Tutorial-and-Notes
ro,u didnt make this tutorial in git hub !!!
bro*
Sorry Uploaded now. Please check
No downloadable resources for this video. If you think you need anything, please post it in the QnA!
Any Course related announcements will be posted here