Python File I/O
This chapter only covers all the basic I/O functions; for more functions, please refer to the Python standard documentation.
Printing to the Screen
The simplest output method is to use the print statement, to which you can pass zero or more comma-separated expressions. 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 appear on your standard screen:
Python 是一个非常棒的语言,不是吗?
Reading keyboard input
Python provides two built-in functions to read a line of text from standard input; the default standard input is the keyboard. As follows:
- raw_input
- input
The raw_input Function
The raw_input([prompt]) function reads a 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 prompts you to enter any string, and then displays the same string on the screen. When I enter "Hello Python!", the output is as follows:
请输入:Hello Python!
你输入的内容是: Hello Python!
The input Function
input([prompt]) function and the raw_input([prompt]) The function is basically similar, but input can accept a Python expression as input and return the result of the evaluation.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = input("请输入:")
print "你输入的内容是: ", str
This produces the following result corresponding to the input:
请输入:[x*5 for x in range(2,10,2)]
你输入的内容是: [10, 20, 30, 40]
Opening and Closing Files
Now you can read from and write to standard input and output. Next, 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 file objects to do most file operations.
The open Function
You must first open a file with Python's built-in open() function to create a file object before the related 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 containing 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. All possible values are shown in the complete list below. This parameter is optional; the default file access mode is read-only (r).
- buffering: If the value of buffering is set to 0, there will be no buffering. If buffering is 1, lines will be buffered when accessing the file. If buffering is set to an integer greater than 1, this indicates the buffer size of the buffering area. If a negative value is used, the buffer size of the buffering area is the system default.
The 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 is raised. |
| b | Binary mode. |
| + | Opens a file for updating (both reading and writing). |
| U | Universal newline mode (not recommended). |
| r | Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. |
| rb | Opens a file in binary format for reading only. The file pointer is placed at the beginning of the file. This is the default mode. Generally used for non-text files such as images. |
| r+ | Opens a file for both reading and writing. The file pointer is placed at the beginning of the file. |
| rb+ | Opens a file in binary format for both reading and writing. The file pointer is placed at the beginning of the file. Generally used for non-text files such as images. |
| w | Opens a file for writing only. If the file exists it is opened and editing starts from the beginning, so the original contents are 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 exists it is opened and editing starts from the beginning, so the original contents are deleted. If the file does not exist, a new file is created. Generally used for non-text files such as images. |
| w+ | Opens a file for both reading and writing. If the file exists it is opened and editing starts from the beginning, so the original contents are deleted. If the file does not exist, a new file is created. |
| wb+ | Opens a file in binary format for both reading and writing. If the file exists it is opened and editing starts from the beginning, so the original contents are deleted. If the file does not exist, a new file is created. Generally used for non-text files such as images. |
| a | Opens a file for appending. If the file exists, the file pointer is placed at the end of the file, so new content is 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 exists, the file pointer is placed at the end of the file, so new content is written after the existing content. If the file does not exist, a new file is created for writing. |
| a+ | Opens a file for both reading and writing. If the file exists, the file pointer is placed at the end of the file and the file is opened in append mode. 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 exists, the file pointer is placed at the end of the file. If the file does not exist, a new file is created for reading and writing. |
The following figure summarizes these modes well:

| Mode | r | r+ | w | w+ | a | a+ |
|---|---|---|---|---|---|---|
| Read | + | + | + | + | ||
| Write | + | + | + | + | + | |
| creation | + | + | + | + | ||
| Overwrite | + | + | ||||
| Pointer at the beginning | + | + | + | + | ||
| Pointer at the end | + | + |
Attributes of the File Object
Once a file is opened, you have a file object from which you can get various information about the file.
The following is a list of all attributes related to the file object:
| property | 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 | Returns false if the file must be followed by a space character when output with print; otherwise returns true. |
The following example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Open a file
fo = open("foo.txt", "w")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace
The example above produces the following output:
文件名: foo.txt
是否已关闭 : False
访问模式 : w
末尾是否强制加空格 : 0
The close() Method
The close() method of a File object flushes any information still in the buffer and closes the file, after which no further writing is possible.
When a reference to a file object is reassigned to another file, Python closes the previous file. It is a good habit to close files with the close() method.
Syntax:
fileObject.close()
Example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Open a file
fo = open("foo.txt", "w")
print "文件名: ", fo.name
# Close open files
fo.close()
The example above produces the following output:
文件名: foo.txt
Reading and Writing Files:
The file object provides a series of methods that make file access easier. Let's see how to use the read() and write() methods to read and write files.
The write() Method
The write() method can write any string to an open file. It is important to note that a Python string 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 open file.
Example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Open a file
fo = open("foo.txt", "w")
fo.write( "www.runoob.com!\nVery good site!\n")
# Close open files
fo.close()
The above method creates the file foo.txt, writes the received content to it, and finally closes the file. If you open this file, you will see the following content:
$ cat foo.txt
www.runoob.com!
Very good site!
The read() Method
The read() method reads a string from an open file. It is important to note that a Python string can be binary data, not just text.
Syntax:
fileObject.read([count])
Here, the parameter passed is the byte count to read from the open file. The method starts reading from the beginning of the file; if no count is passed, it attempts to read as much content as possible, most likely until the end of the file.
Example:
Here we use the foo.txt file created above.
Example
#!/usr/bin/python
-- coding: UTF-8 --
Open a file
fo
=
open
(
"foo.txt"
,
"r+"
)
str
=
fo.
read
(
10
)
"The read string is: "
,
str
Close the opened file
fo.
close
(
)
The example above produces the following output:
读取的字符串是 : www.runoob
File Positioning
The tell() method tells you the current position within the file; in other words, the next read or write will occur after this many bytes from 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, 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. If it is set to 2, the end of the file is used as the reference position.
Example:
Let's 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(10)
print "读取的字符串是 : ", str
# Find current position
position = fo.tell()
print "当前文件位置 : ", position
# Reposition the pointer to the beginning of the file
position = fo.seek(0, 0)
str = fo.read(10)
print "重新读取字符串 : ", str
# Close open files
fo.close()
The example above produces the following output:
读取的字符串是 : www.runoob
当前文件位置 : 10
重新读取字符串 : www.runoob
Renaming and Deleting Files
Python's os module provides methods to help you perform file handling operations, such as renaming and deleting files.
To use this module, you must first import it before you can call its various functions.
The 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 renames an existing file test1.txt.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# Rename file test1.txt to test2.txt.
os.rename( "test1.txt", "test2.txt" )
The remove() Method
You can use the remove() method to delete a file, providing the name of the file to be deleted as a parameter.
Syntax:
os.remove(file_name)
Example:
The following example deletes an existing file test2.txt.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# Delete an existing file test2.txt
os.remove("test2.txt")
Directories in Python:
All files are contained under various directories, but Python can handle them easily. The os module has many methods to help you create, delete, and change directories.
The 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 create.
Syntax:
os.mkdir("newdir")
Example:
The following example creates a new directory test in the current directory.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# Create directory test
os.mkdir("test")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method requires one parameter: the name of the directory you want to set as the current directory.
Syntax:
os.chdir("newdir")
Example:
The following example enters the "/home/newdir" directory.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# Change current directory to "/home/newdir"
os.chdir("/home/newdir")
The 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 the current directory
print os.getcwd()
The rmdir() Method
The rmdir() method deletes a directory; 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
# Delete the "/tmp/test" directory
os.rmdir( "/tmp/test" )
File and Directory Related Methods
File objects and OS objects provide many methods for file and directory operations; you can click the links below for 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.