python删除文本行_使用Python从文本文件中删除特定数量的行

AAAAAAAAAAAAAAAAAAAAA #

BBBBBBBBBBBBBBBBBBBBB #

CCCCCCCCCCCCCCCCCCCCC #

DDDDDDDDDDDDDDDDDDDDD #

EEEEEEEEEEEEEEEEEEEEE #

FFFFFFFFFFFFFFFFFFFFF #

GGGGGGGGGGGGGGGGGGGGG #

HHHHHHHHHHHHHHHHHHHHH #

忽略“#

假设

一直如此。。。

在前两行之后,我想保留三行。。。

最终结果

最终结果应该是这样的:

CCCCCCCCCCCCCCCCCCCCC #

DDDDDDDDDDDDDDDDDDDDD #

EEEEEEEEEEEEEEEEEEEEE #

删除行:前2行+后3行(即第5行之后)的所有内容

要求的

def delete_multiple_lines(original_file, line_numbers):

"""In a file, delete the lines at line number in given list"""

is_skipped = False

counter = 0

# Create name of dummy / temporary file

dummy_file = original_file + '.bak'

# Open original file in read only mode and dummy file in write mode

with open(original_file, 'r') as read_obj, open(dummy_file, 'w') as write_obj:

# Line by line copy data from original file to dummy file

for line in read_obj:

# If current line number exist in list then skip copying that line

if counter not in line_numbers:

write_obj.write(line)

else:

is_skipped = True

counter += 1

# If any line is skipped then rename dummy file as original file

if is_skipped:

os.remove(original_file)

os.rename(dummy_file, original_file)

else:

os.remove(dummy_file)

delete_multiple_lines('sample.txt', [0,1,2])

此方法的问题可能是,如果文件顶部有1-100行要删除,则必须指定[0,1,2…100]。对吗?

回答

由@sandes提供

以下代码将:

删除前63个

忽略其余部分

with open("sample.txt", "r") as f:

lines = f.readlines()

new_lines = []

idx_lines_wanted = [x for x in range(63,((63*2)+95))]

# delete first 63, then get the next 95

for i, line in enumerate(lines):

if i > len(idx_lines_wanted) -1:

break

if i in idx_lines_wanted:

new_lines.append(line)

with open("sample2.txt", "w") as f:

for line in new_lines:

f.write(line)

你可能感兴趣的:(python删除文本行)