📌  相关文章
📜  从文件中删除特定行的Python程序

📅  最后修改于: 2022-05-13 01:55:27.555000             🧑  作者: Mango

从文件中删除特定行的Python程序

在本文中,我们将看到如何使用Python从文件中删除特定行

在整个程序中,作为示例,我们将使用名为months.txt的文本文件,在该文件上将执行各种删除操作。

方法一:使用特定位置删除一行

在此方法中,使用readlines()逐行读取文本文件如果某行的位置与要删除的位置相似,则不会写入新创建的文本文件中。

例子:



Python3
# deleting a line
# based on the position
 
# opening the file in
# reading mode
 
try:
    with open('months.txt', 'r') as fr:
        # reading line by line
        lines = fr.readlines()
         
        # pointer for position
        ptr = 1
     
        # opening in writing mode
        with open('months.txt', 'w') as fw:
            for line in lines:
               
                # we want to remove 5th line
                if ptr != 5:
                    fw.write(line)
                ptr += 1
    print("Deleted")
     
except:
    print("Oops! something error")


Python3
# deleting a line on the basis
# of a matching text (exactly)
 
# we want to remove a line
# with text = '8-August'
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        with open('months_2.txt', 'w') as fw:
            for line in lines:
               
                # strip() is used to remove '\n'
                # present at the end of each line
                if line.strip('\n') != '8-August':
                    fw.write(line)
    print("Deleted")
except:
    print("Oops! something error")


Python3
# deleting a line matching
# a specific pattern or
# containing a specific string
 
# we want to delete a line
# containing string = 'ber'
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        with open('months_3.txt', 'w') as fw:
            for line in lines:
               
                # find() returns -1
                # if no match found
                if line.find('ber') == -1:
                    fw.write(line)
    print("Deleted")
except:
    print("Oops! something error")


Python3
# deleting all the lines that are
# not having the minimum length
# excluding the newline '\n' character
 
# let the min_len = 7
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        min_len = 7
 
        with open('months_4.txt', 'w') as fw:
            for line in lines:
                if len(line.strip('\n')) >= min_len:
                    fw.write(line)
 
    print("Deleted")
except:
    print("Oops! something error")


输出:

Deleted

'5-May' 写在第 5 行,已删除,如下所示:

方法2:使用与该行完全匹配的文本删除该行

在这种方法中,读取文件后,检查每一行是否与给定的文本完全匹配。如果不匹配,则将其写入新文件。

蟒蛇3

# deleting a line on the basis
# of a matching text (exactly)
 
# we want to remove a line
# with text = '8-August'
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        with open('months_2.txt', 'w') as fw:
            for line in lines:
               
                # strip() is used to remove '\n'
                # present at the end of each line
                if line.strip('\n') != '8-August':
                    fw.write(line)
    print("Deleted")
except:
    print("Oops! something error")

输出:

Deleted

确切地说是 '8-August' 的行已被删除,如下所示:



方法 3:使用定制逻辑

示例 1:删除包含指定模式的行

这里,包含指定字符串模式的行被删除。模式可能不一定是整条确切的线。

蟒蛇3

# deleting a line matching
# a specific pattern or
# containing a specific string
 
# we want to delete a line
# containing string = 'ber'
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        with open('months_3.txt', 'w') as fw:
            for line in lines:
               
                # find() returns -1
                # if no match found
                if line.find('ber') == -1:
                    fw.write(line)
    print("Deleted")
except:
    print("Oops! something error")

输出:

Deleted

包含模式 'ber' 的所有行,例如 ' 9-September'、'10-October'、'11-November'、'12-December'都已被删除。

示例 2:删除带有条件的行

如果我们有一个条件,即我们文件中的行必须具有最小长度。因此,以下示例显示了如何删除没有指定最小长度的行。

蟒蛇3

# deleting all the lines that are
# not having the minimum length
# excluding the newline '\n' character
 
# let the min_len = 7
try:
    with open('months.txt', 'r') as fr:
        lines = fr.readlines()
 
        min_len = 7
 
        with open('months_4.txt', 'w') as fw:
            for line in lines:
                if len(line.strip('\n')) >= min_len:
                    fw.write(line)
 
    print("Deleted")
except:
    print("Oops! something error")

输出:

Deleted

删除了所有长度不大于或等于 7 的行: