如何使用Python删除以任何前缀开头的行?
给定一个文本文件,逐行读取该文本文件的内容并仅打印那些不以定义的前缀开头的行。还将这些打印的行存储在另一个文本文件中。可以通过以下方式完成此任务:
方法1:使用循环和 以。。开始()。
在这个方法中,我们逐行读取文件的内容。在阅读时,我们检查该行是否以给定的前缀开头,我们只是跳过该行并打印它。还将该行存储在另一个文本文件中。
示例 1:
假设应该从中读取行的文本文件如下所示:
Python3
# defining object file1 to
# open GeeksforGeeks file in
# read mode
file1 = open('GeeksforGeeks.txt',
'r')
# defining object file2 to
# open GeeksforGeeksUpdated file
# in write mode
file2 = open('GeeksforGeeksUpdated.txt',
'w')
# reading each line from original
# text file
for line in file1.readlines():
# reading all lines that do not
# begin with "TextGenerator"
if not (line.startswith('TextGenerator')):
# printing those lines
print(line)
# storing only those lines that
# do not begin with "TextGenerator"
file2.write(line)
# close and save the files
file2.close()
file1.close()
Python3
# importing regex module
import re
# defining object file1 to open
# GeeksforGeeks file in read mode
file1 = open('GeeksforGeeks.txt',
'r')
# defining object file2 to open
# GeeksforGeeksUpdated file in
# write mode
file2 = open('GeeksforGeeksUpdated.txt','w')
# reading each line from original
# text file
for line in file1.readlines():
# reading all lines that begin
# with "TextGenerator"
x = re.findall("^Geeks", line)
if not x:
# printing those lines
print(line)
# storing only those lines that
# do not begin with "TextGenerator"
file2.write(line)
# close and save the files
file1.close()
file2.close()
输出:
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets containing TextGenerator passages, and more recently with desktop publishing software like Albus Potter including versions of TextGenerator.
在上面的示例中,我们打开一个文件并逐行读取其内容。我们使用startswith()方法检查该行是否以给定的前缀开头。 如果该行以“TextGenerator”开头,我们跳过该行,否则我们打印该行并将其存储在另一个文件中。这样,我们可以删除以指定前缀开头的行。
方法 2:使用正则表达式。
在这种方法中,我们使用Python的re 模块,它提供了一组元字符。元字符是具有特殊含义的字符。要删除以指定前缀开头的行,我们使用“^”(开头为)元字符。
我们还使用了re.findall()函数,它返回一个包含所有匹配项的列表。
Python3
# importing regex module
import re
# defining object file1 to open
# GeeksforGeeks file in read mode
file1 = open('GeeksforGeeks.txt',
'r')
# defining object file2 to open
# GeeksforGeeksUpdated file in
# write mode
file2 = open('GeeksforGeeksUpdated.txt','w')
# reading each line from original
# text file
for line in file1.readlines():
# reading all lines that begin
# with "TextGenerator"
x = re.findall("^Geeks", line)
if not x:
# printing those lines
print(line)
# storing only those lines that
# do not begin with "TextGenerator"
file2.write(line)
# close and save the files
file1.close()
file2.close()
输出:
forGeeksGeeks
在上面的示例中,我们打开一个文件并逐行读取其内容。我们使用正则表达式检查该行是否以“Geeks”开头。如果该行以“Geeks”开头,我们跳过该行,并打印其余行并将这些行存储在另一个文件中。