欢迎访问宙启技术站
智能推送

Python中文件IO操作的函数使用

发布时间:2023-06-06 03:28:47

Python中文件IO操作的函数主要集中在内置的open()函数和文件对象的一些方法上。下面对这些函数及其使用进行详细介绍。

1. open()函数

open()函数用于打开一个文件,并返回一个文件对象。函数需要一个文件名作为参数,并且可以传递多个可选参数,如modeencoding等。常见的使用方式为:

file = open('file.txt', 'r', encoding='utf-8')

其中,r表示读取模式,encoding表示文件编码,若不加上此参数,Python将使用默认编码(通常为GBK)。

2. 文件对象的读取方法

文件对象有三种读取方式:read()readline()readlines()

- read()用于从文件读取指定的字节数或全部内容。如果不传参数,则读取整个文件。语法:

  file.read([size])
  

示例:

  file = open('file.txt', 'r', encoding='utf-8')
  content = file.read()  # 读取整个文件
  file.close()
  

- readline()用于读取文件的一行内容。语法:

  file.readline()
  

示例:

  file = open('file.txt', 'r', encoding='utf-8')
  line1 = file.readline()  # 读取      行
  line2 = file.readline()  # 读取第二行
  file.close()
  

- readlines()用于读取整个文件中的所有行,并返回一个包含所有行的列表。语法:

  file.readlines()
  

示例:

  file = open('file.txt', 'r', encoding='utf-8')
  lines = file.readlines()  # 读取所有行
  file.close()
  

3. 文件对象的写入方法

文件对象的写入方法包括write()writelines()

- write()用于向文件写入指定字符串。语法:

  file.write(str)
  

示例:

  file = open('file.txt', 'w', encoding='utf-8')
  file.write('Hello World!')  # 写入一行字符串
  file.close()
  

- writelines()用于向文件写入多行字符串,其所传参数为一个列表。语法:

  file.writelines(list_of_strings)
  

示例:

  file = open('file.txt', 'w', encoding='utf-8')
  file.writelines(['Hello World!', 'Goodbye World!'])  # 写入多行字符串
  file.close()
  

4. 文件对象的其他方法

- close()用于关闭一个文件。语法:

  file.close()
  

示例:

  file = open('file.txt', 'r', encoding='utf-8')
  content = file.read()
  file.close()  # 关闭文件
  

- seek()用于移动文件指针到指定位置。语法:

  file.seek(offset[, whence])
  

参数offset表示偏移量,参数whence表示起始位置。

- 如果whence被省略,则offset表示从文件开头开始的位置。

- 如果whence为0,则offset表示从文件开头开始的位置。

- 如果whence为1,则offset表示从当前位置开始的位置。

- 如果whence为2,则offset表示从文件末尾开始的位置。

示例:

  file = open('file.txt', 'rb') # 二进制文件需要使用'b'模式打开
  file.seek(10)  # 将指针移动到文件的第10个字节处
  content = file.read()
  file.close()
  

5. 上下文管理器

上下文管理器可以自动管理资源,它在Python3.0引入了一个新的语法:with语句。使用with语句可以自动关闭文件,无需调用close()方法。示例:

with open('file.txt', 'r', encoding='utf-8') as file:
    content = file.read()

with语句块中使用file对象时,file对象在with语句块执行完毕后会自动关闭。此法相比使用try...finally语句手动关闭文件更为便捷。

6. 示例

使用Python实现写入和读取文件的示例代码:

# 写入文件
with open('file.txt', 'w', encoding='utf-8') as file:
    file.write('Hello World!
')
    file.write('Goodbye World!
')

# 读取文件
with open('file.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())

代码输出:

Hello World!
Goodbye World!