Home  >  Article  >  Backend Development  >  What are the ways to read and write files in Python?

What are the ways to read and write files in Python?

WBOY
WBOYOriginal
2023-10-20 15:42:16729browse

What are the ways to read and write files in Python?

There are many ways to read and write files in Python, and you can choose different methods according to actual needs. The following will introduce several commonly used file reading and writing methods, and give code examples.

  1. Using the open() function
    The open() function is a built-in function provided by Python for opening files. It accepts a filename and opening mode as parameters and returns a file object.
    Code example:
# 打开文件
file = open("file.txt", "w")
# 写入文件
file.write("Hello, world!")
# 关闭文件
file.close()

# 打开文件
file = open("file.txt", "r")
# 读取文件内容
content = file.read()
print(content)
# 关闭文件
file.close()
  1. Use the with statement
    Use the with statement to automatically close the file after the file operation is completed, without manually calling the close() method.
    Code example:
# 写入文件
with open("file.txt", "w") as file:
    file.write("Hello, world!")

# 读取文件
with open("file.txt", "r") as file:
    content = file.read()
    print(content)
  1. Use read() and write() methods
    File objects have read() and write() methods, which can be used for reading and writing respectively Write file contents.
    Code example:
# 打开文件
file = open("file.txt", "w")
# 写入文件
file.write("Hello, world!")
# 关闭文件
file.close()

# 打开文件
file = open("file.txt", "r")
# 读取部分内容
content = file.read(5)
print(content)
# 关闭文件
file.close()
  1. Use readline() and writelines() methods
    The file object also has readline() and writelines() methods, which can be used line by line respectively. Read and write file contents.
    Code example:
# 打开文件
file = open("file.txt", "w")
# 写入多行内容
lines = ["line 1", "line 2", "line 3"]
file.writelines(lines)
# 关闭文件
file.close()

# 打开文件
file = open("file.txt", "r")
# 逐行读取文件内容
line = file.readline()
while line:
    print(line)
    line = file.readline()
# 关闭文件
file.close()

The above are several commonly used file reading and writing methods, which are suitable for different scenarios and needs. When using functions and methods related to file reading and writing, you must remember to close the file in time to avoid problems such as resource leakage.

The above is the detailed content of What are the ways to read and write files 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