Python File I/O
This chapter only covers all basic I/O functions. For more functions, please refer to the Python standard documentation.
Printing to the Screen
The simplest way to output is to use the print statement, where you can pass it zero or more expressions separated by commas. This function converts the expressions you pass into a string expression and writes the result to standard output as follows:
#!/usr/bin/python # -*- coding: UTF-8 -*- print "Python 是一个非常棒的语言,不是吗?"
The following result will be displayed on your standard screen:
Python 是一个非常棒的语言,不是吗?
Reading Keyboard Input
Python provides two built-in functions to read a line of text from standard input, which defaults to the keyboard. As follows:
- raw_input
- input
raw_input function
The raw_input([prompt]) function reads one line from standard input and returns a string (with the trailing newline removed):
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = 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:
请输入:Hello Python! 你输入的内容是: Hello Python!
input function
input([prompt])function andraw_input([prompt])The functions are basically similar, but input can receive a Python expression as input and return the result of the operation.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = input("请输入:")
print "你输入的内容是: ", str
This will produce results corresponding to the input as follows:
请输入:[x*5 for x in range(2,10,2)] 你输入的内容是: [10, 20, 30, 40]
Opening and Closing Files
Now that you can read from 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 operations by default. You can use thefilefile object to perform most file operations.
open function
You must first open a file using Python's built-in open() function to create a file object, and then the relevant methods can be called to read and write it.
Syntax:
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 in which the file is opened: read-only, write, append, etc. See the complete list of all possible values below. This parameter is optional, and the default file access mode is read-only (r).
- buffering: If buffering is set to 0, no buffering is performed. If buffering is set to 1, lines are buffered when accessing files. If buffering is set to an integer greater than 1, it indicates the buffer size of the buffering area. If a negative value is used, the buffer size is the system default.
Complete list of modes for opening files:
| Mode | Description |
|---|---|
| t | Text mode (default). |
| x | Write mode, creates a new file; if the file already exists, an error will be reported. |
| b | Binary mode. |
| + | Opens a file for updating (readable and writable). |
| U | Universal newline mode (not recommended). |
| r | Opens 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. Generally used for non-text files such as images, etc. |
| r+ | Opens 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. Generally used for non-text files such as images, etc. |
| w | Opens a file for writing only. If the file already exists, it opens the file and edits from the beginning, meaning the original contents will be deleted. If the file does not exist, a new file is created. |
| wb | Opens a file in binary format for writing only. If the file already exists, it opens the file and edits from the beginning, meaning the original contents will be deleted. If the file does not exist, a new file is created. Generally used for non-text files such as images, etc. |
| w+ | Opens a file for reading and writing. If the file already exists, it opens the file and edits from the beginning, meaning the original contents will be deleted. If the file does not exist, a new file is created. |
| wb+ | Opens a file in binary format for reading and writing. If the file already exists, it opens the file and edits from the beginning, meaning the original contents will be deleted. If the file does not exist, a new file is created. Generally used for non-text files such as images, etc. |
| a | Opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, new content will be written after the existing content. If the file does not exist, a new file is created for writing. |
| 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. That is, new content will be written after the existing content. If the file does not exist, a new file is created for writing. |
| a+ | Opens a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be in append mode when opened. If the file does not exist, a new file is created for reading and writing. |
| 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, a new file is created for reading and writing. |
The following diagram summarizes these modes well:

| Mode | r | r+ | w | w+ | a | a+ |
|---|---|---|---|---|---|---|
| read | + | + | + | + | ||
| write | + | + | + | + | + | |
| Create | + | + | + | + | ||
| Overwrite | + | + | ||||
| Pointer at start | + | + | + | + | ||
| Pointer at end | + | + |
File Object Attributes
Once a file is opened, you have a file object and can obtain various information about the file.
The following is a list of all attributes related to the file object:
| Attribute | Description |
|---|---|
| file.closed | Returns true if the file has been closed, otherwise returns false. |
| file.mode | Returns the access mode of the opened file. |
| file.name | Returns the name of the file. |
| file.softspace | If after printing with print, a space character must follow, returns false. Otherwise, returns true. |
The following example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开一个文件
fo = open("foo.txt", "w")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace
The above example outputs the following result:
文件名: foo.txt 是否已关闭 : False 访问模式 : w 末尾是否强制加空格 : 0
close() method
The close() method of a File object flushes any information still not written in the buffer and closes the file, after which no more writing can be performed.
When a file object's reference is reassigned to another file, Python will close the previous file. It is a good habit to close files using the close() method.
Syntax:
fileObject.close()
Example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开一个文件
fo = open("foo.txt", "w")
print "文件名: ", fo.name
# 关闭打开的文件
fo.close()
The above example outputs the following result:
文件名: foo.txt
Reading and Writing Files:
The file object provides a series of methods that make our file access easier. Let's see how to use the read() and write() methods to read and write files.
write() method
The write() method can write any string to an opened file. It is important to note that Python strings can be binary data, not just text.
The write() method does not add a newline character ('\n') at the end of the string:
Syntax:
fileObject.write(string)
Here, the parameter passed is the content to be written to the opened file.
Example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开一个文件
fo = open("foo.txt", "w")
fo.write( "www.example.com!\nVery good site!\n")
# 关闭打开的文件
fo.close()
The above method will create a foo.txt file, write the received content to it, and finally close the file. If you open this file, you will see the following content:
$ cat foo.txt www.example.com! Very good site!
read() method
The read() method reads a string from an opened file. It is important to note that Python strings can be binary data, not just text.
Syntax:
fileObject.read([count])
Here, the parameter passed is the byte count to be read from the opened file. This method starts reading from the beginning of the file. If count is not passed, it will try to read as much content as possible, likely until the end of the file.
Example:
Here we use the foo.txt file created above.
Example
# -*- coding: UTF-8 -*-
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "The read string is: ", str
# Close the opened file
fo.close()
The above example outputs the following result:
读取的字符串是 : www.example
File Positioning
The tell() method tells you the current position within the file. In other words, the next read or write will occur that many bytes after the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset variable indicates the number of bytes to move. The from variable specifies the reference position from which to start moving bytes.
If from is set to 0, it means the beginning of the file is used as the reference position for moving bytes. If set to 1, the current position is used as the reference position. If it is set to 2, then the end of the file will be used as the reference position.
Example:
Use the file foo.txt we created above.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10)
print "读取的字符串是 : ", str
# 查找当前位置
position = fo.tell()
print "当前文件位置 : ", position
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0)
str = fo.read(10)
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()
The output of the above example is:
读取的字符串是 : www.example 当前文件位置 : 10 重新读取字符串 : www.example
Renaming and Deleting Files
Python's os module provides methods that 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 call various 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:
The following example will rename an existing file, test1.txt.
#!/usr/bin/python # -*- coding: UTF-8 -*- import os # 重命名文件test1.txt到test2.txt。 os.rename( "test1.txt", "test2.txt" )
remove() method
You can use the remove() method to delete files, and you need to provide the name of the file to be deleted as a parameter.
Syntax:
os.remove(file_name)
Example:
The following example will delete an existing file, test2.txt.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")
Directories in Python:
All files are contained in various different directories, but Python can handle them easily. The os module has many methods that can 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 containing the name of the directory to be created.
Syntax:
os.mkdir("newdir")
Example:
The following example will create a new directory, test, in the current directory.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# 创建目录test
os.mkdir("test")
chdir() method
You can use the chdir() method to change the current directory. The parameter that the chdir() method requires is the name of the directory you want to set as the current directory.
Syntax:
os.chdir("newdir")
Example:
The following example will go into the "/home/newdir" directory.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# 将当前目录改为"/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/python # -*- coding: UTF-8 -*- import os # 给出当前的目录 print os.getcwd()
rmdir() method
The rmdir() method deletes a directory, and the directory name is passed as a parameter.
Before deleting this directory, all of its contents should be cleared first.
Syntax:
os.rmdir('dirname')
Example:
The following is an example of deleting the "/tmp/test" directory. The fully qualified name of the directory must be given, otherwise the directory will be searched for in the current directory.
#!/usr/bin/python # -*- coding: UTF-8 -*- import os # 删除”/tmp/test”目录 os.rmdir( "/tmp/test" )
File and Directory Related Methods
File objects and OS objects provide many methods for operating on files and directories. You can click the links below to view details:
- File Object Methods: The file object provides a series of methods for operating on files.
- OS Object Methods: Provides a series of methods for handling files and directories.