File Operations in Python programming,
Open Function
You must first use the Python built-in open () function to open a file and create a file object. The related auxiliary methods can call it for read and write.
Syntax:
file object = open(file_name [, access_mode][, buffering])
The parameters are described as follows:
File_name: The file_name variable is a string value that contains the name of the file you want to access.
Access_mode: access_mode determines the file opening mode: Read-only, write, append, and so on. For all values, see the complete list below. This parameter is not mandatory. The default file access mode is read-only (r ).
Buffering: If the buffering value is set to 0, there will be no storage. If the buffering value is set to 1, the row is stored when the file is accessed. If the buffering value is set to an integer greater than 1, it indicates the buffer size of the storage zone. If the value is negative, the buffer size in the storage area is the default value.
Complete list of open files in different modes:
File object attributes
After a file is opened, you have a file object. You can obtain various information about the file.
The following lists all attributes related to the file object:
Example:
#! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("foo.txt", "wb") print "Name of the file: ", fo. nameprint "Closed or not:", fo. closedprint "Opening mode:", fo. modeprint "Softspace flag:", fo. softspace
Output result of the above instance:
Name of the file: foo.txtClosed or not : FalseOpening mode : wbSoftspace flag : 0
Close () method
The close () method of the File object refreshes any unwritten information in the buffer and closes the File, so that no data can be written.
When a reference to a file object is re-specified to another file, Python will close the previous file. Close () is a good habit.
Syntax:
fileObject.close();
Example:
#! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("foo.txt", "wb") print "Name of the file: ", fo. name # Close the open file fo. close ()
Output result of the above instance:
Name of the file: foo.txt
Read/write files:
File objects provide a series of methods to make file access easier. To see how to use the read () and write () Methods to read and write files.
Write () method
The Write () method can Write any string into an open file. It is important to note that Python strings can be binary data rather than text.
The Write () method does not end with a string and does not add a line break ('\ n '):
Syntax:
fileObject.write(string);
Here, the passed parameter is the content to be written to the opened file.
Example :#! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("/tmp/foo.txt", "wb") fo. write ("Python is a great language. \ nYeah its great !! \ N "); # close the open file fo. close ()
The preceding statement creates the foo.txt file, writes the received content to the file, and closes the file. If you open this file, you will see the following:
Python is a great language.Yeah its great!!
Read () method
The read () method reads a string from an open file. It is important to note that Python strings can be binary data rather than text.
Syntax:
fileObject.read([count]);
Here, the passed parameter is the byte count to be read from the opened file. This method is read from the beginning of the file. If count is not input, it will try to read as much content as possible, probably until the end of the file.
Example:
Use the foo.txt file created in our workshop.
#! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("/tmp/foo.txt", "r +") str = fo. read (10); print "Read String is:", str # Close open file fo. close ()
Output result of the above instance:
Read String is : Python is
File Location:
The Tell () method tells you the current position in the file. In other words, the next read/write will happen after the beginning of the file so many bytes:
The seek (offset [, from]) method changes the location of the current file. The Offset variable indicates the number of bytes to be moved. The From variable specifies the reference position for starting to move bytes.
If from is set to 0, it means that the start of the file is used as the reference location for moving byte. If it is set to 1, the current location is used as the reference location. If it is set to 2, the end of the file will be used as the reference location.
Example:
Use the foo.txt file created in our workshop.
#! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("/tmp/foo.txt", "r +") str = fo. read (10); print "Read String is:", str # Find the current position = fo. tell (); print "Current file position:", position # re-locate the pointer to the beginning of the file position = fo. seek (0, 0); str = fo. read (10); print "Again read String is:", str # Close open file fo. close ()
Output result of the above instance:
Read String is : Python isCurrent file position : 10Again read String is : Python is
Rename and delete objects
The Python OS module provides methods to help you perform file processing operations, such as renaming and deleting files.
To use this module, you must first import it and then call related functions.
Rename () method:
The rename () method requires two parameters: the current file name and the new file name.
Syntax:
os.rename(current_file_name, new_file_name)
Example:
In the following example, a file test1.txt already exists.
#! /Usr/bin/python #-*-coding: UTF-8-*-import OS # rename file test1.txtto test2.txt. OS. rename ("test1.txt", "test2.txt ")
Remove () method
You can use the remove () method to delete a file. You need to provide the file name to be deleted as a parameter.
Syntax:
os.remove(file_name)
Example:
In the following example, a file test2.txt already exists will be deleted.
#! /Usr/bin/python #-*-coding: UTF-8-*-import OS # delete an existing file test2.txt OS. remove ("text2.txt ")