在Python中删除行的方法有很多种。以下是几种常见的方法:
lines = ['line 1\n', 'line 2\n', 'line 3\n', 'line 4\n']
lines = [line for line in lines if 'line 2' not in line]
lines = ['line 1\n', 'line 2\n', 'line 3\n', 'line 4\n']
del lines[1]
lines = ['line 1\n', 'line 2\n', 'line 3\n', 'line 4\n']
lines.pop(1)
lines = ['line 1\n', 'line 2\n', 'line 3\n', 'line 4\n']
lines.remove('line 2\n')
with open('file.txt', 'r') as file:
lines = file.readlines()
with open('file.txt', 'w') as file:
for line in lines:
if 'line 2' not in line:
file.write(line)
这些方法可以根据实际需要选择使用,具体取决于你的需求和代码实现的方式。