This article introduces the basic operations for input and output of python File 1. Python File I/O
This chapter only describes all basic I/O functions. for more functions, see The Python Standard Documentation.
2. print to the screen
The simplest output method is to use the print statement. you can pass zero or multiple expressions separated by commas. This function converts your passed expression into 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 # @ Author: wwyxprint "python is an object-oriented language"
The result of running Example 1 is as follows:
Python is an object-oriented language.
3. read keyboard input
Python provides two built-in functions to read a line of text from the standard input. the default standard input is the keyboard. As follows:
Raw_input function
Raw_input ([prompt]) function reads a row from the standard input and returns a string (remove the line break at the end ):
Example 2:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxstrs = raw_input ("Enter the string you want to enter: ") print" the string you entered is: ", strs
Example 2 running result:
Enter the string you want to enter: python the string you entered is: python
Input function
The input ([prompt]) function is similar to the raw_input ([prompt]) function, but the input can receive a Python expression as the input and return the operation result.
Example 3:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxinputStr = input ("input expression :") print "run the input result:", inputStr
Example 3 running result:
Input expression: [x * 4 for x in (2, 3, 4)] run the input result: [8, 12, 16]
4. open and close files
Now, you can read and write to standard input and output. Now let's take a look at how to read and write the actual data files.
Python provides the necessary functions and methods for basic file operations by default. You can use a file object for most file operations.
Open function
You must use the Python built-in open () function to open a file and create a file object before calling it for read/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, and append. 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, no storage will be available. 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 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 reading and writing. The file pointer will be placed at the beginning of the file.
Rb + opens 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 opens a file in binary format and is only used for writing. 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 + opens 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 opens 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 + opens 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 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:
Attribute description
File. closedReturns true if the object is closed; otherwise, returns false.
File. modeReturns the access mode of the opened file.
File. nameThe name of the returned file.
File. softspaceIf 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 # @ Author: wwyxfiletest = open ("file.txt", "wb ") print "whether the file is closed:", filetest. closedprint "file mode:", filetest. modeprint "File name:", filetest. nameprint "whether to add a space at the end:", filetest. softspace
Example 4 running 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 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 5
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxfiletest = open ("file.txt", "wb ") print "whether the file is closed:", filetest. closedprint "file mode:", filetest. modeprint "File name:", filetest. nameprint "whether to add a space at the end:", filetest. softspaceprint "close the file! "Filetest. close () # close File print" file closed successfully! "
Result 5:
Disable file: False file mode: wb File name: file.txt whether to force a space at the end: 0 to close the file! File closed successfully!
5. read and 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 canStringWrite an open file. Note that PythonThe 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);
Here, the passed parameter is the content to be written to the opened file.
Example 6
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxfiletest = open ("file.txt", "wb ") filetest. write ("python programming language can be used in many places") print "close the file! "Filetest. close () # close File print" file closed successfully! "Print" re-open the file! "Filetest = open (" file.txt "," rb ") strs = filetest. read (1024) print" file content: ", strs
Example 6 running result:
Close the file! File closed successfully! Open the file again! My file 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 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 6
6 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 7:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxfiletest = open ("file.txt", "wb ") filetest. write ("python programming language can be used in many places") # open the file filetest = open ("file.txt", "rb") strs = filetest. read (10) print "file content:", strs # locate the file location p = filetest. tell () print "current file location", p # reset the file read location filetest. seek (0, 0) print "file location reset successfully !!! "Print" the file read after resetting the pointer location "strs = filetest. read (10) print" the file content is: ", strsprint" close the file! "Filetest. close () # close File print" file closed successfully! "
Example 7 running result:
The file content is: the current position of the python file is 10. the file location is reset successfully !!! The file content read after resetting the pointer position is: close the file in python! File closed successfully!
7. rename and delete files
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 before calling 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 8:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyximport osfiletest = open ("myfile.txt", "wb ") # filetest. write ("python basic learning") # disabled after annual check! Filetest. close () # Rename the OS file. rename ("myfile.txt", "renamefile.txt") print "the renamed file name is:", filetest. name # open the renamed File fileremane = open ("renamefile.txt", "r") strs = fileremane in read-only mode. read (100) print "File name:", fileremane. nameprint "the content of the modified file after reading is:", strs
Example 8 running result:
The renamed file name is myfile.txt.
File name: renamefile.txt
The content of the modified file is: python basics
Note: If the relevant name file already exists under the Directory, an exception occurs when you rename the file.
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 9
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyximport osfiletest = open ("myfile.txt", "wb ") # filetest. write ("python basic learning") # disabled after annual check! Filetest. close () # delete the file OS. remove ("myfile.txt") # Re-read the deleted file filetest = open ("myfile.txt", "rb") # print the file content print "the file content is:", filetest. read (10)
Example 9 running result
Traceback (most recent call last): File "E:/python/hello/untitled3/filetest.py", line 14, in
filetest = open("myfile.txt", "rb")IOError: [Errno 2] No such file or directory: 'myfile.txt'
Running result: an exception is reported because a deleted file is read.
8. 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 () method
You 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")
Chdir () method
You can use the chdir () method to change the current directory and directory path. A parameter required by the chdir () method is the directory name of the current directory.
Syntax:
os.chdir("newdir")
Getcwd () method
The getcwd () method displays the current working directory.
Syntax:
os.getcwd()
Rmdir () method
Delete 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 10:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyximport OS # Create a directory OS. mkdir ("mydir") # obtain the current directory nowdir = OS. getcwd () print "current directory:", nowdir # locate the directory and modify the directory path OS. chdir ("mydir") # obtain the modified directory path updatedir = OS. getcwd () print "the modified current directory is:", updatedirind = updatedir. rfind ("\") print "truncated string", indprint "type:", type (updatedir) newdir = updatedir [0: int (ind)] print "new dir", newdir # locate the directory and modify the directory path OS. chdir (newdir) # obtain the modified directory path updatedir = OS. getcwd () print "the modified current directory is:", updatedir # Delete the directory OS. rmdir ("mydir") # obtain the deleted directory path deletedir = OS. getcwd () print "the modified current directory is:", deletedir
Example 10 running result:
The current directory: E: \ python \ hello \ untitled3. the modified current directory is: E: \ python \ hello \ untitled3 \ mydir. the intercepted string 25 type:
The current directory modified by new dir E: \ python \ hello \ untitled3 is: E: \ python \ hello \ untitled3. the modified directory is: E: \ python \ hello \ untitled3.
9. file and directory Related methods
Three important methods can be used to extensively and practically process and manipulate files and directories on Windows and Unix operating systems, as follows:
The above is a detailed description of the basic operation methods for File input and output in python files. For more information, see other related articles in the first PHP community!