在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)
這些方法可以根據實際需要選擇使用,具體取決于你的需求和代碼實現的方式。