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:
Mode |
Description |
R |
Open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode. |
Rb |
Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. |
R + |
Open a file for reading and writing. The file pointer will be placed at the beginning of the file. |
Rb + |
Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. |
W |
Open a file for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file. |
Wb |
Open a file in binary format for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file. |
W + |
Open a file for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file. |
Wb + |
Open a file in binary format for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file. |
A |
Open a file for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing. |
AB |
Open a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing. |
A + |
Open a file for reading and writing. If the file already exists, the file pointer is placed at the end of the file. When the file is opened, the append mode is used. If the file does not exist, create a new file for reading and writing. |
AB + |
Open a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, create a new file for reading and writing. |
File object attributesAfter 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:
Attribute |
Description |
File. closed |
Returns true if the object is closed; otherwise, returns false. |
File. mode |
Returns the access mode of the opened file. |
File. name |
The name of the returned file. |
File. softspace |
If the print output must be followed by a space character, false is returned. Otherwise, true is returned. |
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 () methodThe 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 () methodThe 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 () methodThe 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 objectsThe 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 () methodYou 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 ("test2.txt ")
Directory in Python:All files are included in different directories, but Python can easily process them. The OS module has many ways to help you create, delete, and change directories.
Mkdir () methodYou can use the mkdir () method of the OS module to create new directories in the current directory. You need to provide a parameter that contains the name of the directory to be created.
Syntax:
os.mkdir("newdir")
Example:
In the following example, a new directory named test is created under the current directory.
#! /Usr/bin/python #-*-coding: UTF-8-*-import OS # create directory testos. mkdir ("test ")
Chdir () methodYou can use the chdir () method to change the current directory. A parameter required by the chdir () method is the Directory Name of the current directory.
Syntax:
os.chdir("newdir")
Example:
The following example will go to the "/home/newdir" directory.
#! /Usr/bin/python #-*-coding: UTF-8-*-import OS # change the current directory to "/home/newdir" OS. chdir ("/home/newdir ")
Getcwd () method:
The getcwd () method displays the current working directory.
Syntax:
os.getcwd()
Example:
The following example shows the current directory:
#! /Usr/bin/python #-*-coding: UTF-8-*-import OS # Give the current directory OS. getcwd ()
Rmdir () methodDelete the directory by using the rmdir () method. The directory name is passed as a parameter.
Before deleting this directory, all its contents should be cleared first.
Syntax:
os.rmdir('dirname')
Example:
The following is an example of deleting the "/tmp/test" directory. The full compliance name of the directory must be given; otherwise, the directory will be searched in the current directory.
#! /Usr/bin/python #-*-coding: UTF-8-*-import OS # Delete "/tmp/test" directory OS. rmdir ("/tmp/test ")
File and directory related methodsThree important methods can be used to extensively and practically process and manipulate files and directories on Windows and Unix operating systems, as follows:
- File object method: The file object provides a series of methods for operating files.
- OS object method: provides a series of methods to process files and directories.