Delete Line in File Python Guide
To delete a line, you need to rewrite the file using file operations and skip the line that is not needed. Here is an example code:
def delete_line(file_path, line_number):
with open(file_path, 'r') as file:
lines = file.readlines()
with open(file_path, 'w') as file:
for index, line in enumerate(lines):
if index != line_number - 1: # 跳过需要删除的行
file.write(line)
# 示例使用
delete_line('example.txt', 3) # 删除第3行
In this example, the delete_line function takes the file path and the line number to be deleted as parameters. It first opens the file and reads the contents into a list. Then, it opens the same file again in write mode, and writes the contents by iterating through the list, skipping the line that needs to be deleted. Make sure to replace ‘example.txt’ with the actual file path you want to work with, and 3 with the actual line number you want to delete.