Hướng dẫn python remove first line from file - python xóa dòng đầu tiên khỏi tệp

Tôi đã tìm kiếm trực tuyến, nhưng không tìm thấy bất kỳ giải pháp tốt nào.

Đây là tệp văn bản của tôi:

[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]
[24, 28, 38, 37, 9, 44, -14, 84, -40, -92, 86, 94, 95, -62, 12, -36, -12]
[-26, -67, -89, -7, 12, -20, 76, 88, -15, 38, -89, -65, -53, -84, 31, -81, -91]
[-19, -50, 16, 47, -42, -31, 75, 0, 25, -95, 75, 97, 19, 77, -2, -31, -59]
[-66, -10, 35, -39, 24, 70, 74, -45, -27, 77, -44, 86, 57, 14, -91, -26, -20]
[-63, 80, -31, 70, 100, 22, -30, 74, 44, -35, -25, -75, -39, -13, -93, 0, 1]
[63, 13, 67, 55, -56, 45, 10, 61, -14, -55, 40, 84, -59, 7, 75, -64, -25]
[7, -50, -17, -86, -43, 34, 82, 84, 49, 18, 56, -31, -19, 59, -96, 72, -40]
[-73, 34, -68, 20, 30, 1, 49, 77, -94, 2, -83, 40, 2, 20, 66, 60, -36]
[-80, -12, 93, 77, 73, -55, 24, 3, -60, 12, -41, -43, -49, 36, 6, -93, -24]
[-41, 12, -43, 42, -70, 75, -84, -83, 30, 78, -3, 51, 69, 0, 65, 60, -15]
[82, 97, -57, -96, 25, -100, 61, 13, -80, -32, 99, 60, 58, -58, -45, -58, -53]
[-90, -34, 80, 95, -12, -34, 71, -83, 46, 10, -78, -40, 65, 53, -81, 40, -59]
[-80, -20, -87, -2, -54, 74, -79, 22, -20, 60, -84, -12, -40, -98, -81, -5, -35]
[33, 36, -46, 10, -77, 88, -99, -5, 19, -20, 89, 87, -47, 46, 10, 17, -67]
[-77, 73, 20, 44, 79, -14, -8, -49, 45, -49, -91, -21, 41, -13, 74, -71, -15]
[98, -99, 51, 53, 56, -78, 31, 45, 35, -36, -10, -86, 9, 94, 24, -2, -20]
[-37, 46, -77, -92, 48, -34, 75, 19, -74, -13, -100, 33, -46, 19, -60, 5, 5]
[-13, -30, -82, -70, 64, 87, 16, 67, -36, 22, -99, -92, 36, 8, 90, 48, -5]
[46, 75, -15, 24, 24, -37, -3, -45, 32, -84, -2, -16, 43, -88, 92, 27, -10]

Tất cả những gì tôi muốn là xóa dòng đầu tiên (có nghĩa là sử dụng dòng thứ hai làm dòng đầu tiên, không điền vào dòng đầu tiên bằng khoảng trắng).

Bất cứ ai có thể vui lòng giúp tôi với điều đó?

Bài viết này cho bạn biết cách xóa các dòng cụ thể khỏi một tệp trong Python. Ví dụ: bạn muốn xóa các dòng #5 và #12.

Sau khi đọc bài viết này, bạn sẽ học::

  • Cách xóa các dòng cụ thể khỏi tệp theo số dòng
  • Cách xóa các dòng khớp hoặc chứa văn bản/chuỗi đã cho
  • Cách xóa dòng đầu tiên và cuối cùng khỏi tệp văn bản.

Xóa các dòng khỏi một tệp theo số dòng

Vui lòng làm theo các bước dưới đây để xóa các dòng cụ thể khỏi tệp văn bản theo số dòng: -

  1. Mở tệp ở chế độ đọc
  2. Đọc một tập tin. Đọc tất cả nội dung từ một tệp vào danh sách bằng phương thức
    # list to store file lines
    lines = []
    # read file
    with open(r"E:\demos\files\sample.txt", 'r') as fp:
        # read an store all lines into list
        lines = fp.readlines()
    
    # Write file
    with open(r"E:\demos\files\sample.txt", 'w') as fp:
        # iterate each line
        for number, line in enumerate(lines):
            # delete line 5 and 8. or pass any Nth line you want to remove
            # note list index starts from 0
            if number not in [4, 7]:
                fp.write(line)
    7. Ở đây mỗi phần tử của danh sách là một dòng từ tệp
  3. Đóng một tập tin
  4. Một lần nữa, mở cùng một tệp trong chế độ ghi.
  5. Lặp lại tất cả các dòng từ một danh sách sử dụng hàm for loop và liệt kê (). Hàm
    # list to store file lines
    lines = []
    # read file
    with open(r"E:\demos\files\sample.txt", 'r') as fp:
        # read an store all lines into list
        lines = fp.readlines()
    
    # Write file
    with open(r"E:\demos\files\sample.txt", 'w') as fp:
        # iterate each line
        for number, line in enumerate(lines):
            # delete line 5 and 8. or pass any Nth line you want to remove
            # note list index starts from 0
            if number not in [4, 7]:
                fp.write(line)
    8 thêm một bộ đếm vào một điều có thể (chẳng hạn như danh sách, chuỗi) và trả về nó trong việc liệt kê đối tượng. Chúng tôi đã sử dụng đối tượng liệt kê với một vòng lặp để truy cập số dòng
  6. Sử dụng điều kiện IF trong mỗi lần lặp của một vòng để kiểm tra số dòng. Nếu nó khớp với số dòng để xóa, thì don don viết dòng đó vào tệp.
  7. Đóng một tập tin

Example::

Một lần nữa, mở cùng một tệp trong chế độ ghi.how to delete lines from a text file by line number in Python. See the attached file used in the example and an image to show the file’s content for reference.

Hướng dẫn python remove first line from file - python xóa dòng đầu tiên khỏi tệp
Lặp lại tất cả các dòng từ một danh sách sử dụng hàm for loop và liệt kê (). Hàm
# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
8 thêm một bộ đếm vào một điều có thể (chẳng hạn như danh sách, chuỗi) và trả về nó trong việc liệt kê đối tượng. Chúng tôi đã sử dụng đối tượng liệt kê với một vòng lặp để truy cập số dòng

Sử dụng điều kiện IF trong mỗi lần lặp của một vòng để kiểm tra số dòng. Nếu nó khớp với số dòng để xóa, thì don don viết dòng đó vào tệp.deleting lines 5 and 8.

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)

Mã sau đây hiển thị & nbsp; cách xóa các dòng khỏi tệp văn bản theo số dòng & nbsp; trong python. Xem tệp đính kèm được sử dụng trong ví dụ và hình ảnh để hiển thị nội dung tệp để tham khảo.

First line
Second line
Third line
Fourth line
Sixth line
Seventh line

Note::

Tệp văn bản

Trong ví dụ này, chúng tôi là & nbsp; xóa các dòng 5 và 8.: Don’t use

First line
Second line
Third line
Fourth line
Sixth line
Seventh line
4 keywords to delete lines from a list and write the same list to file. Because when you delete a line from the list, the item’s index gets changed. So you will no longer be able to delete the correct line.

Mã của chúng tôi đã xóa hai dòng. Đây là dữ liệu hiện tại của một tệp

Hàm

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
8 thêm một bộ đếm vào một điều có thể sử dụng được (chẳng hạn như danh sách, chuỗi) và trả về nó trong đối tượng
First line
Second line
Third line
Fourth line
Sixth line
Seventh line
0. Chúng tôi đã sử dụng đối tượng
First line
Second line
Third line
Fourth line
Sixth line
Seventh line
0 với vòng lặp
First line
Second line
Third line
Fourth line
Sixth line
Seventh line
2 để truy cập số dòng.
# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
8 không tải toàn bộ danh sách trong bộ nhớ, vì vậy đây là một giải pháp hiệu quả. don’t need to open a file twice.

  • Lưu ý: Don Tiết sử dụng từ khóa
    First line
    Second line
    Third line
    Fourth line
    Sixth line
    Seventh line
    4 để xóa các dòng khỏi danh sách và viết cùng một danh sách vào tệp. Bởi vì khi bạn xóa một dòng khỏi danh sách, chỉ mục của mục sẽ được thay đổi. Vì vậy, bạn sẽ không còn có thể xóa đúng dòng.read and write mode (
    First line
    Second line
    Third line
    Fourth line
    Sixth line
    Seventh line
    5)
  • Sử dụng phương thức Seek ()
  • Điều tương tự có thể được thực hiện bằng phương thức Seek () bằng cách thay đổi vị trí con trỏ để chúng tôi không cần phải mở một tệp hai lần.pointer to the start of a file using
    First line
    Second line
    Third line
    Fourth line
    Sixth line
    Seventh line
    6 method
  • Mở tệp trong chế độ đọc và ghi (
    First line
    Second line
    Third line
    Fourth line
    Sixth line
    Seventh line
    5)
  • Đọc tất cả các dòng từ một tệp vào danh sách
  • Di chuyển con trỏ tệp đến đầu tệp bằng phương thức
    First line
    Second line
    Third line
    Fourth line
    Sixth line
    Seventh line
    6

Example::

with open(r"E:\demos\files\sample.txt", 'r+') as fp:
    # read an store all lines into list
    lines = fp.readlines()
    # move file pointer to the beginning of a file
    fp.seek(0)
    # truncate the file
    fp.truncate()

    # start writing lines
    # iterate line and line number
    for number, line in enumerate(lines):
        # delete line number 5 and 8
        # note: list index start from 0
        if number not in [4, 7]:
            fp.write(line)

Cắt ngắn tệp bằng phương pháp First line Second line Third line Fourth line Sixth line Seventh line7

Lặp lại danh sách bằng cách sử dụng chức năng Loop và

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
8

Trong mỗi lần lặp viết dòng hiện tại vào tệp. Bỏ qua những số dòng mà bạn muốn xóa.

  • Xóa dòng đầu tiên và cuối cùng của một tệp
  • Để xóa một cách chọn lọc một số nội dung nhất định khỏi tệp, chúng tôi cần sao chép nội dung của tệp ngoại trừ các dòng chúng tôi muốn xóa và viết lại các dòng còn lại vào cùng một tệp.
  • Sử dụng các bước dưới đây để xóa dòng đầu tiên khỏi một tệp.
  • Mở tệp ở chế độ đọc và ghi (
    First line
    Second line
    Third line
    Fourth line
    Sixth line
    Seventh line
    5)
  • Đọc tất cả các dòng từ một tệp
with open(r"E:\demos\files\sample.txt", 'r+') as fp:
    # read an store all lines into list
    lines = fp.readlines()
    # move file pointer to the beginning of a file
    fp.seek(0)
    # truncate the file
    fp.truncate()

    # start writing lines except the first line
    # lines[1:] from line 2 to last line
    fp.writelines(lines[1:])

Di chuyển con trỏ tệp khi bắt đầu tệp bằng phương thức

First line
Second line
Third line
Fourth line
Sixth line
Seventh line
6

Cắt ngắn tệp

First line
Second line
Third line
Fourth line
Sixth line
Seventh line

Viết tất cả các dòng từ một tệp ngoại trừ dòng đầu tiên.

Second line
Third line
Fourth line
Sixth line
Seventh line

Đầu ra.

# lines[N:] to delete first 5 lines
fp.writelines(lines[4:])

Trước khi xóa dòng đầu tiên

# read from second line
lines = fp.readlines()[1:]

Sau khi xóa dòng đầu tiên

with open(r"E:\demos\files\sample.txt", 'r+') as fp:
    # read an store all lines into list
    lines = fp.readlines()
    # move file pointer to the beginning of a file
    fp.seek(0)
    # truncate the file
    fp.truncate()

    # start writing lines except the last line
    # lines[:-1] from line 0 to the second last line
    fp.writelines(lines[:-1])

Để xóa các dòng đầu tiên sử dụng Danh sách cắt..

Nếu bạn đang đọc một tệp và don lồng muốn đọc dòng đầu tiên, hãy sử dụng phương pháp dưới đây thay vì xóa một dòng khỏi một tệp.

Sử dụng ví dụ dưới đây để các bước để xóa dòng cuối cùng khỏi tệp

Để xóa n dòng cuối cùng, sử dụng danh sách cắt.

Steps::

  • # list to store file lines
    lines = []
    # read file
    with open(r"E:\demos\files\sample.txt", 'r') as fp:
        # read an store all lines into list
        lines = fp.readlines()
    
    # Write file
    with open(r"E:\demos\files\sample.txt", 'w') as fp:
        # iterate each line
        for number, line in enumerate(lines):
            # delete line 5 and 8. or pass any Nth line you want to remove
            # note list index starts from 0
            if number not in [4, 7]:
                fp.write(line)
    0
  • Mở cùng một tệp trong chế độ ghi
  • Lặp lại một danh sách và ghi từng dòng vào một tệp ngoại trừ các dòng khớp với chuỗi đã cho.

Ví dụ 1: Xóa các dòng khớp với văn bản đã cho (khớp chính xác): Delete lines that match the given text (exact match)

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
1

Ngoài ra, bạn có thể đạt được nó bằng cách sử dụng vòng lặp duy nhất để nó sẽ nhanh hơn nhiều.single loop so it will be much faster.

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
2

Xóa các dòng chứa một từ cụ thể

Chúng tôi có thể phải xóa các dòng khỏi một tệp chứa một từ khóa hoặc thẻ cụ thể trong một số trường hợp. Hãy cùng xem ví dụ để xóa các dòng khỏi tệp có chứa một chuỗi cụ thể ở bất cứ đâu trong dòng.

Example::

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
3

Xóa các dòng bắt đầu bằng từ/chuỗi cụ thể

Tìm hiểu cách xóa các dòng khỏi một tệp bắt đầu bằng một từ cụ thể. Trong ví dụ sau, chúng tôi sẽ xóa các dòng bắt đầu bằng từ ‘Thời gian.time‘.

Example::

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
4

Xóa văn bản cụ thể khỏi tệp văn bản

Nó cũng có thể là trường hợp bạn muốn xóa một chuỗi cụ thể khỏi một tệp nhưng không phải là dòng chứa nó. Hãy cùng xem ví dụ về cùng một

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
5

Để xóa tất cả các dòng trong một tệp và xóa tệp, chúng ta có thể sử dụng phương thức cắt ngắn () trên đối tượng tệp. Phương thức cắt () loại bỏ tất cả các dòng khỏi một tệp và đặt con trỏ tệp đến đầu tệp.

# list to store file lines
lines = []
# read file
with open(r"E:\demos\files\sample.txt", 'r') as fp:
    # read an store all lines into list
    lines = fp.readlines()

# Write file
with open(r"E:\demos\files\sample.txt", 'w') as fp:
    # iterate each line
    for number, line in enumerate(lines):
        # delete line 5 and 8. or pass any Nth line you want to remove
        # note list index starts from 0
        if number not in [4, 7]:
            fp.write(line)
6