Home  >  Article  >  Backend Development  >  What are the options for file reading and writing modes in Python?

What are the options for file reading and writing modes in Python?

WBOY
WBOYOriginal
2023-10-20 16:39:201160browse

What are the options for file reading and writing modes in Python?

Python is a powerful programming language that provides a variety of file reading and writing modes to meet different needs. This article will introduce the commonly used file reading and writing modes in Python and give corresponding code examples.

  1. Read mode ('r')
    Read mode is the most commonly used file reading and writing mode, used to read existing files. In read mode, the file pointer is at the beginning of the file, and the file cannot be written to.

Sample code:

# 打开文件
file = open('example.txt', 'r')

# 读取文件内容
content = file.read()

# 关闭文件
file.close()

# 打印文件内容
print(content)
  1. Write mode ('w')
    Write mode is used to create a new file or overwrite an existing file. In write mode, the file pointer is located at the beginning of the file, and writing data will overwrite the original content. If the file does not exist, a new file will be created.

Sample code:

# 打开文件
file = open('example.txt', 'w')

# 写入内容
file.write('Hello, World!')

# 关闭文件
file.close()
  1. Append mode ('a')
    Append mode is used to add new content to the end of the file without overwriting the original content. If the file does not exist, a new file will be created.

Sample code:

# 打开文件
file = open('example.txt', 'a')

# 追加内容
file.write('Hello, World!')

# 关闭文件
file.close()
  1. Read-write mode ('r ')
    Read-write mode can both read and modify file contents. The file pointer is located at the beginning of the file, and writing will overwrite the original content.

Sample code:

# 打开文件
file = open('example.txt', 'r+')

# 读取文件内容
content = file.read()
print(content)

# 在文件开头写入新内容
file.seek(0)
file.write('Hello, Python!')

# 关闭文件
file.close()
  1. Binary mode ('b')
    Binary mode is used to process binary files, such as images, audio, etc. In binary mode, file contents are read and written in bytes.

Sample code:

# 打开二进制文件
file = open('example.jpg', 'rb')

# 读取文件内容
content = file.read()

# 关闭文件
file.close()

The above is the commonly used file reading and writing mode in Python. Select the appropriate mode according to specific needs to operate files efficiently.

The above is the detailed content of What are the options for file reading and writing modes in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn