This chapter only covers all the basic I/O functions, and more functions refer to the Python standard documentation.
Print to screen
The simplest way to output this is to use the print statement, which you can pass 0 or more comma-separated expressions. This function converts the expression you pass to a string expression and writes the result to the standard output as follows:
# !/usr/bin/python Print " Python is really a great language, " " isn ' t it? ";
The following results are produced on your standard screen:
is really a great language, isn't it?
Reading keyboard input
Python provides two built-in functions to read a line of text from standard input, and the default standard input is the keyboard. As follows:
Raw_input function
The Raw_input ([prompt]) function reads a line from the standard input and returns a string (minus the end of the newline character):
# !/usr/bin/python = raw_input (""); Print " ", str
This will prompt you to enter any string and then display the same string on the screen. When I enter "Hello python! ", its output is as follows:
is: Hello Python
Input function
The input ([prompt]) function and the raw_input ([prompt]) function are basically interchangeable, but input assumes that your input is a valid Python expression and returns the result of the operation.
# !/usr/bin/python = input (""); Print " ", str
This will produce the following results for the input:
for in range (2,10,2 are: [10, 20, 30, 40]
Opening and closing files
Until now, you have been able to read and write to standard input and output. Now, let's see how to read and write actual data files.
Python provides the necessary functions and methods for basic file operation by default. You can use the file object to do most of the document operations.
Open function
You must first open a file with the Python built-in open () function, create a Document object, and the associated helper method can call it for read and write.
Grammar:
File Object = open (file_name [, access_mode][, Buffering])
The details of each parameter are as follows:
- The File_name:file_name variable is a string value that contains the name of the file you want to access.
- Access_mode:access_mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).
- Buffering: If the value of buffering is set to 0, there is no deposit. If the value of buffering is 1, the row is stored when the file is accessed. If you set the value of buffering to an integer greater than 1, it indicates that this is the buffer size of the storage area. If a negative value is taken, the buffer size of the storage area is the system default.
Full list of open files in different modes:
Mode |
Description |
R |
Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode. |
Rb |
Opens 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 read-write. The file pointer will be placed at the beginning of the file. |
rb+ |
Opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file. |
W |
Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. |
Wb |
Open a file in binary format only for writing. Overwrite the file if it already exists. If the file does not exist, create a new file. |
w+ |
Open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. |
wb+ |
Opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. |
A |
Opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. |
Ab |
Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. |
A + |
Open a file for read-write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write. |
ab+ |
Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write. |
Properties of the File object
After a file is opened, you have a files object that you can get various information about the file.
The following is a list of all properties related to the file object:
Properties |
Description |
File.closed |
Returns true if the file has been closed, otherwise false is returned. |
File.mode |
Returns the access mode of the file being opened. |
File.name |
Returns the name of the file. |
File.softspace |
If the print output must be followed by a space character, false is returned. Otherwise, returns True. |
The following example:
#!/usr/bin/python #Open a fileFO = open ("foo.txt","WB")Print "Name of the file:", Fo.namePrint "Closed or not:", fo.closedPrint "Opening mode:", Fo.modePrint "softspace flag:", Fo.softspace
The result of the above example output:
Name of the file: or not : Falseopening mode: wbsoftspace flag: 0
Close () method
The close () method of the file object flushes any information that has not yet been written in the buffer and closes the file, which can no longer be written.
When a reference to a file object is re-assigned to another file, Python closes the previous file. Closing a file with the close () method is a good habit.
Grammar:
Fileobject.close ();
Example:
# !/usr/bin/python # Open a file fo = open ("foo.txt""wb") Print""# Close Open file fo.close ()
The result of the above example output:
Name of the file: foo.txt
Read and Write files:
The file object provides a series of methods that make it easier to access our files. Take a look at how to read and write to the file using the read () and write () methods.
Write () method
The write () method writes any string to an open file. It is important to note that the Python string can be binary data, not just text.
The Write () method does not add a line break (' \ n ') at the end of the string:
Grammar:
Fileobject.write (string);
Here, the parameter being passed is the content to be written to the open file.
Example:
# !/usr/bin/python # Open a file fo = open ("/tmp/foo.txt""wb" " Python is a great language.\nyeah its great!! \ n"# Close Open file fo.close ()
The above method creates a Foo.txt file, writes the received content to the file, and eventually closes the file. If you open this file, you will see the following:
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 the Python string can be binary data, not just text.
Grammar:
Fileobject.read ([count]);
Here, the parameter being passed is the count of bytes to read from the open file. The method reads in from the beginning of the file, and if it does not pass in count, it tries to read as much more content as possible, most likely until the end of the file.
Example:
Just use the file Foo.txt we created above.
# !/usr/bin/python # Open a file fo = open ("/tmp/foo.txt""r+"= Fo.read (ten); Print " ", str# Close Open file fo.close ()
The result of the above example output:
Read String is: Python is
File Location:
The tell () method tells you the current position within the file, in other words, the next read and write occurs after so many bytes at the beginning of the file:
The Seek (offset [, from]) method changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.
If from is set to 0, this means that the beginning of the file is used as the reference location for moving bytes. If set to 1, the current position is used as the reference location. If it is set to 2, then the end of the file will be used as the reference location.
Example:
Just use the file Foo.txt we created above.
#!/usr/bin/python #Open a fileFO = open ("/tmp/foo.txt","r+") Str= Fo.read (10);Print "Read String is:", str#Find Current LocationPosition =Fo.tell ();Print "Current file Position:", Position#Reposition The pointer again to the beginning of the filePosition =fo.seek (0, 0); Str= Fo.read (10);Print "Again Read String is:", str#Close an open fileFo.close ()
The result of the above example output:
is: are current file position: are: is
Renaming and deleting files
Python's OS module provides a way to help you perform file processing operations, such as renaming and deleting files.
To use this module, you must first import it, and then you can invoke the various functions associated with it.
Rename () Method:
The rename () method requires two parameters, the current file name, and a new filename.
Grammar:
Os.rename (Current_file_name, New_file_name)
Example:
The following example renames a file that already exists test1.txt.
# !/usr/bin/python Import # rename files test1.txt to Test2.txt. "test1.txt" "test2.txt ")
Remove () method
You can delete the file using the Remove () method, and you need to provide the filename to delete as a parameter.
Grammar:
Os.remove (file_name)
Example:
The following example deletes a file that already exists test2.txt.
# !/usr/bin/python Import # Delete a file that already exists Test2.txtos.remove ("text2.txt")
Directories in Python:
All files are contained in different directories, but Python is also easy to handle. The OS module has many ways to help you create, delete, and change directories.
mkdir () method
You can use the mkdir () method of the OS module to create new catalogs in the current directory. You need to provide a parameter that contains the name of the directory you want to create.
Grammar:
Os.mkdir ("newdir")
Example:
The following example creates a new catalog test under the current directory.
# !/usr/bin/python Import # Create directory Testos.mkdir ("test")
ChDir () method
You can use the ChDir () method to change the current directory. The ChDir () method requires a parameter that you want to set as the directory name of the current directory.
Grammar:
Os.chdir ("newdir")
Example:
The following example goes to the "/home/newdir" directory.
# !/usr/bin/python Import # Change the current directory to "/home/newdir"os.chdir ("/home/newdir")
GETCWD () Method:
The GETCWD () method displays the current working directory.
Grammar:
OS.GETCWD ()
Example:
The following example gives the current directory:
# !/usr/bin/python Import # give the current directory OS.GETCWD ()
RmDir () method
The RmDir () method deletes the directory, and the directory name is passed as a parameter.
Before deleting this directory, all of its contents should be purged first.
Grammar:
Os.rmdir ('dirname')
Example:
The following is an example of deleting the "/tmp/test" directory. The fully compliant name of the directory must be given, otherwise the directory will be searched under the current directory.
# !/usr/bin/python Import # Delete "/tmp/test" directory "/tmp/test" )
File, directory-related methods
Three important method sources can be used for a wide and practical processing and manipulation of files and directories on Windows and UNIX operating systems, as follows:
- File Object method: The File object provides a series of methods for manipulating files.
- OS Object methods: Provides a series of methods for working with files and directories.
|
This article is based on the attribution 2.5 China mainland license Agreement published, welcome reprint, deduction or for commercial purposes, but must and in the article page obvious location give the original link Dana, Li (including link), the specific operation method can refer here. If you have any questions or authorization to negotiate, please leave a message or add Q Group! |
Python file I/O