A file is a resource that is used for saving data and information in the hardware of the computer
there are various mode of opening a file
r : r mode opens a file for read-only. We do not have permission to update or change any data in this mode.
w : w mode does not concern itself with what is present in the file. It just opens a file for writing and if there is
already some data present in the file, it overwrites it.
x : x is used to create a new file. It does not work for an already existing file, as in such cases the operation fails.
a : a stands for append, which means to add something to the end of the file. It does exactly the same.
It just adds the data we like in write(w) mode but instead of overwriting it just adds it to the end of the file.
It also does not have the permission of reading the file.
t : t mode is used to open our file in text mode and only proper text files can be opened by it.
It deals with the file data as a string.
b : b stands for binary and this mode can only open the binary files,
that are read in bytes. The binary files include images, documents, or all other files that require specific
software to be read.
+ : In plus mode, we can read and write a file simultaneously.
The mode is mostly used in cases where we want to update our file.
after reading the above description about the files
1.how to open a file:-
a file can be opened using the built-in open function in python
syntax of the open function is
open("file name " , "mode")
to open the file we must specify two things .
1. name of the file along with its extension
2. the mode in which we want to open it
the above file will open in rt mode as it is the default mode
open function returns file as an object . we will store the object in a variable called the file pointer
2. How to read a file:-
there are various methods available to read a file.
1.we can use read() method that reads the entire file at once or
2.read(size) method that reads the size provided'''
content = f.read()
'''we can also use readline method to read individual lines of the code'''
print(f.readline()) # reads only one line at a time
print(f.readlines()) # reads all the lines and returns a list of them
'we can also use loops in the file
content = f.read()
for lines in f:
number of characters written can be printed by storing f.write() in a variable as done below
a= f.write("\n Enjoy Python ")
append mode will also create a new file , like the write mode if it is not present
various functions that can be used with files
1. seek() functon , it shifts the file ponter to the desired line
2 . tell() it tells where exactly the file pointer is'''
it is a very good practice to close a file
file s closed by
Using files with Block :-
in python we can also open the files using the “with” block .with takes care of closing the file and we need not close the files separately
syntax with open("xyz.txt","rt") as f : . '''
with open("python.txt","rt") as f: