Python File close() Method

Python File(文件) 方法Python File Methods


Overview

close()The method is used to close an opened file. After closing, the file can no longer be read or written; otherwise, it will triggerValueErroran error. The close() method can be called multiple times.

When a file object is referenced to operate on another file, Python automatically closes the previous file object. Using the close() method to close files is a good habit.

Syntax

The syntax of the close() method is as follows:

fileObject.close();

Parameters

  • None

Return Value

This method has no return value.

Example

The following example demonstrates the use of the close() method:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("example.txt", "wb")
print "文件名为: ", fo.name

# 关闭文件
fo.close()

The output of the above example is:

文件名为:  example.txt

Python File(文件) 方法Python File Methods

Other Extensions