How do we open and close files in python?
Last updated Aug 13, 2021Python File Open and Close operations
You can also manipulate the actual data, read it change it, etc., some functions help in manipulating the files. Most of the files manipulation can be done by using a function file. So before starting file handling one must understand the use of opening and closing of files. The FIle can be opened in reading (r) or write.
Here we will learn how to opn and close the files in python
The open function
Open function is used to open python files. We have to open a file before making any changes to the file. There is a python inbuilt function to open a file that is open() which supports another method to be utilized associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering]) |
file_name –the name of the file that you want to access.
access_mode- in which mode file will be accessed some are:-
r- open the file in the reading mode
file = open('code.txt', 'r') |
you can read the file and also print the file on screen.
w- open the file in reading mode, you can update the file and if the file is not there the command will make a new file.
file = open('code.txt','w') file.write("updating code////") |
a- open the file in append format. The file pointer is at the end of the file if the file exists, and if the file is not there the command will make a new file.
file = open('code.txt','a') file.write("This will add this line") |
r+ = opening of the file in reading and writing mode. The pointer in the file will be a beginning.
file = open('code.txt','r+') file.write("This will add this line") for each in file: print (each) |
buffering- useful as a way to expose the binary data from another object to the Python programmer.
The file object attribute
This attribute is used to get various information related to that file.
- File.close= print “Closed or not : “, fo.closed – returns true if file is closed otherwise false
- File.mode= print “Opening mode: “, fo.mode- tells in which mode file is open
- File.name= print “Name of the file: “, fo.name- returns name of file
- File.softspace= print “Softspace flag : “, fo.softspace- Returns false if space explicitly required with print, true otherwise.
Close method()
It is used to close a file, after which no access will be there with the file unless you open it once again.
SYNTAX -
fileobject.close() |
Let's understand this with a help of an example:-
file = open('code.txt','w') file.write("It allows us to write in a particular file") file.close() |
The above given example is used for closing a file.
Article Contributed By :
|
|
|
|
154 Views |