How to perform file operations in Python
File operations are one of the common tasks in programming, and Python provides rich file operation functions and concise syntax to Help us read, write and process files efficiently. This article will introduce how to perform file operations in Python and provide some specific code examples.
Before performing file operations, you first need to use the open()
function to open the file, and after the operation is completed Use the close()
function to close the file.
file = open("data.txt", "r") # 以只读模式打开名为data.txt的文件 # 进行文件操作 file.close() # 关闭文件
open()
The first parameter of the function is the path of the file, and the second parameter is the file opening mode. Common modes include:
Python provides a variety of ways to read the contents of files. Common methods are:
read()
: Read the entire file content at one time readline()
: Read the content of one line of the filereadlines()
: Read all lines of the file and return a list # 一次性读取整个文件内容 file = open("data.txt", "r") content = file.read() file.close() # 逐行读取文件内容 file = open("data.txt", "r") for line in file.readlines(): print(line) file.close()
is similar to reading the file, Python also provides a variety of ways to write the contents of files.
write()
: Write the specified content at one time writelines()
: Write a list of strings, each The string represents a line# 一次性写入内容 file = open("output.txt", "w") file.write("Hello, World!") file.close() # 逐行写入内容 lines = ["Line 1", "Line 2", "Line 3"] file = open("output.txt", "w") file.writelines(lines) file.close()
Copying a file is one of the common tasks of file operations, which can be achieved by reading and writing. .
# 复制文件 file1 = open("source.txt", "r") file2 = open("destination.txt", "w") content = file1.read() file2.write(content) file1.close() file2.close()
In Python, you can use the remove()
function of the os
module to delete files.
import os os.remove("data.txt") # 删除名为data.txt的文件
Each open file has a pointer that identifies the current read and write location. You can use the seek()
function to change the position of the file pointer.
file = open("data.txt", "r") file.seek(5) # 将文件指针移动到第6个字节的位置(从0开始计数) content = file.read() # 从当前位置开始读取文件内容 print(content) file.close()
The above are the basic usage methods and sample codes for file operations in Python. In practical applications, you can also combine exception handling, regular expressions and other functions to perform more complex file operations. I hope this article can help readers better understand and use Python for file operations.
The above is the detailed content of How to do file operations in Python. For more information, please follow other related articles on the PHP Chinese website!