Original blog, reprint please indicate the source--Zhou Xuewei http://www.cnblogs.com/zxouxuewei/
This chapter only covers all the basic I/O functions, and more functions refer to the Python standard documentation.
One. 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/-*-coding:utf-8 -*-"Python is a great language, isn't it? "; your standard screen will produce the following results: Python is a great language, isn't it?
Two. Read 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/-*-coding:utf-8 -*- = raw_input (" Please enter:" "" , 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: Please enter: Hello python! The content you entered is: Hello python!
Input function
The
input ([prompt]) function and the raw_input ([prompt]) function are basically similar, but input can receive a Python expression as input. and returns the result of the operation.
#!/usr/bin/-*-coding:utf-8 -*- = input (" Please enter:" " ", str This will produce the following corresponding input results: Please enter: [x*5 for in range (2 ,2)] The content you entered is: [tento40 ]
Three. Open and close files
You can now read and write to standard inputs and outputs. 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 related method can call it for read and write.
Grammar:
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. |
Four. 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#-*-coding:utf-8-*-# Open a file fo= Open ("foo.txt","WB") Print"file name:", Fo.nameprint"is closed:", Fo.closedprint"access mode:", Fo.modeprint"whether to force a space at the end:", fo.softspace The above instance output: File name: Foo.txt is closed: false access mode: The end of WB is forced to add a space:0Close () 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.
syntax: Fileobject.close (); Example: #!/usr/bin/-*-coding:utf-8 -*-= open (" Foo.txt"wb""", Fo.name # Close Open File Fo.close () above instance output: File name: 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:
syntax: Fileobject.write (string), where the passed argument is the content to be written to the open file. Example: #!/usr/bin/-*-coding:utf-8 -*-= open ("foo.txt" "WB""www.runoob.com!\nvery good site!\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: $ cat foo.txt www.runoob.com! Very Good site!
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:
Here we use the Foo.txt file created above.
#!/usr/bin/-*-coding:utf-8 -*-= open ("foo.txt"" r+ " = fo.read("", str# close Open file Fo.close () The above example output: The string read is: www.runoob file Location:
Five. Document positioning
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#-*-coding:utf-8-*-# Open a file fo= Open ("foo.txt","r+") Str= Fo.read (Ten);p rint"the string to read is:", str # find current location position=Fo.tell ();p rint"Current file location:", Position # reposition the pointer again to the beginning of the file position= Fo.seek (0,0); Str= Fo.read (Ten);p rint"To re-read the string:", str# closes the Open file Fo.close () above the instance output: The string read is: Www.runoob the current file location:Tenre-reading string: Www.runoobSix. 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 before 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.
syntax: Os.rename (Current_file_name, New_file_name) Example: The following example renames a file that already exists test1.txt. #!/usr/bin/-*-coding:utf-8 -*-"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.
syntax: Os.remove (file_name) Example: The following example deletes a file test2.txt that already exists. #!/usr/bin/-*-coding:utf-8 -*-import OS # Delete a file that already exists Test2.txtos.remove (" Test2.txt ")
Seven. 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.
syntax: Os.mkdir ("newdir") Example: The following example creates a new directory in the current directory test. #!/usr/bin/-*-coding:utf-8 -*-import OS # 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.
syntax: Os.chdir ("newdir") Example: The following example will enter " /home/newdir " directory. #!/usr/bin/-*-coding:utf-8 -*-import OS # Changes 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 gives the current directory: #!/usr/bin/-*-coding:utf-8 -*-import OS # gives the current directory print 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.
syntax: os.rmdir ('dirname') Example: The following is a delete " /tmp/test " examples of catalogs. The fully compliant name of the directory must be given, otherwise the directory will be searched under the current directory. #!/usr/bin/-*-coding:utf-8 -*-import os # delete "/tmp/" /tmp/test" )
Eight. File and 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.
python--file i/o--11