Tag: EFI BSP from date determines traceback action file used to receive
1. Python File I/O
This chapter only covers all the basic I/O functions, and more functions refer to the Python standard documentation.
2. 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:
Example 1:
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : Wwyxprint "Python is an object-oriented language"
Running Example 1 results in the following:
Python is an object-oriented language
3. 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):
Example 2:
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : wwyxstrs = raw_input ("Please enter the string you want to enter : ") print" The string you entered is: ", STRs
Example 2 run Result:
Please enter the string you want to enter: Python The string you entered is: Python
Input function
The input ([prompt]) function is basically similar to the raw_input ([prompt]) function, but input can receive a Python expression as input and return the result of the operation.
Example 3:
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : wwyxinputstr = input ("Can enter expression:") p Rint "Run input result:", inputstr
Example 3 run Result:
You can enter an expression: [X*4 for X in (2,3,4)] runs the input result: [8, 12, 16]
4. 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:
File Object = open (file_name [, access_mode][, Buffering]
The details of each parameter are 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 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:
Pattern description
- R opens the file in read-only mode. 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 opens a file for writing only. 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 writing only. 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 + opens a file for read and 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:
Property 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, 0 is returned. Otherwise, 1 is returned.
Example 4
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : wwyxfiletest = open ("File.txt", " WB ") print" file is closed: ", filetest.closedprint" file mode: ", filetest.modeprint" file name: ", Filetest.nameprint" is forced to add a space at the end: ", Filetest.softspace
Example 4 run Result:
Whether the file is closed: false file Mode: WB file name: file.txt whether to force a space at the end: 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 5
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : wwyxfiletest = open ("File.txt", " WB ") print" file is closed: ", filetest.closedprint" file mode: ", filetest.modeprint" file name: ", Filetest.nameprint" is forced to add a space at the end: ", Filetest.softspaceprint "Close the file! "Filetest.close () # Close File print" File closed successfully! "
Example 5 results:
Whether the file is closed: false file Mode: WB file name: file.txt force at the end with a space: 0 close the file! File closed successfully!
5. 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 6
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : wwyxfiletest = open ("File.txt", " WB ") Filetest.write (" Python programming language can be used in many places ") print" Close file! " "Filetest.close () # Close File print" File closed successfully! "Print" re-open Read file! "Filetest = open (" file.txt "," RB ") STRs = Filetest.read (1024x768) print" File My content is: ", STRs
Example 6 run Result:
Close the file! File closed successfully! Re-open Read file! My content is: Python programming language can be used in many places
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.
Use Case Reference Example 6
6 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 7:
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : wwyxfiletest = open ("File.txt", " WB ") Filetest.write (" Python programming language can be used in many places ") # Open File Filetest = open (" file.txt "," RB ") STRs = Filetest.read () print" File content is: " , strs# position file location P = Filetest.tell () print "File current Location", p# reset file read location Filetest.seek (0, 0) print "Reset file location successfully!!!" Print "file read after reset pointer position" STRs = Filetest.read (Ten) print "File content is:", Strsprint "close the file!" "Filetest.close () # Close File print" File closed successfully! "
Example 7 Run Result:
The file content is: Python files current location 10 reset the file location successfully!!! After you reset the position of the pointer, the contents of the file read are: Python to close the file! File closed successfully!
7. 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.
Grammar:
Os.rename (Current_file_name, New_file_name)
Example 8:
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : Wwyximport osfiletest = open ("Myf Ile.txt "," WB ") # File Write content filetest.write (" Python Basic Learning ") # not closed for annual inspection! Filetest.close () # File renamed Os.rename ("MyFile.txt", "Renamefile.txt") print "renamed file name is:", filetest.name# Open Rename file as read-only fileremane = open ("Renamefile.txt", "r") STRs = Fileremane.read () print "File name:", Fileremane.nameprint " After reading the modified file, the content is: ", STRs
Example 8 Run Result:
The renamed file name is: myfile.txt
File name: Renamefile.txt
Read the modified file content is: Python basic learning
Note: If the relevant name file already exists under the directory, then the rename will be unexpected
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 9
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : Wwyximport osfiletest = open ("Myf Ile.txt "," WB ") # File Write content filetest.write (" Python Basic Learning ") # not closed for annual inspection! Filetest.close () # Delete file Os.remove ("MyFile.txt") # re-read deleted file Filetest = open ("MyFile.txt", "RB") # Print out the contents of the file "file content is:", Filetest.read (10)
Example 9 Run Results
Traceback (most recent): File "e:/python/hello/untitled3/filetest.py", line <module> filetest = open ("MyFile.txt", "RB") IOError: [Errno 2] No such file or directory: ' MyFile.txt '
Run Result: The exception is reported because a deleted file is read
8. 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")
ChDir () method
You can use the ChDir () method to change the current directory and modify the directory path. The ChDir () method requires a parameter that you want to set as the directory name of the current directory.
Grammar:
Os.chdir ("Newdir")
GETCWD () method
The GETCWD () method displays the current working directory.
Grammar:
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 10:
#!/usr/bin/env python#-*-coding:utf-8-*-# @Time : 2016/9/25 15:12# @Author : Wwyximport os# Create a directory Os.mkdir ("my Dir ") # get current directory Nowdir = OS.GETCWD () print" Current directory: ", nowdir# relocate directory, modify directory path Os.chdir (" Mydir ") # Get modified directory path Updatedir = OS.GETCWD () print "Modified current directory is:", Updatedirind = Updatedir.rfind ("\ \") print "truncated string", Indprint "type:", type (updatedir) Newdir = Updatedir[0:int (Ind)]print "New dir", newdir# relocate directory, modify directory path Os.chdir (newdir) # Get modified directory path Updatedir = OS.GETCWD () print " The modified current directory is: ", updatedir# Delete directory Os.rmdir (" Mydir ") # Gets the deleted directory path Deletedir = OS.GETCWD () print" Modified current directory is: ", Deletedir
Example 10 Run Result:
Current directory: E:\python\hello\untitled3 the modified current directory is: E:\python\hello\untitled3\mydir truncated string 25type: <type ' str ' >new dir E : \python\hello\untitled3 Modified current directory is: E:\python\hello\untitled3 modified the current directory is: E:\PYTHON\HELLO\UNTITLED3
9. 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 Efficient Use (10) ——— file, input and output basic operations