Hướng dẫn how do you skip the first line while reading a file in python? - làm thế nào để bạn bỏ qua dòng đầu tiên khi đọc tệp trong python?

Để khái quát hóa nhiệm vụ đọc nhiều dòng tiêu đề và để cải thiện khả năng đọc, tôi sẽ sử dụng trích xuất phương pháp. Giả sử bạn muốn mã hóa ba dòng đầu tiên của

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens
2 để sử dụng làm thông tin tiêu đề.

Thí dụ

coordinates.txt
---------------
Name,Longitude,Latitude,Elevation, Comments
String, Decimal Deg., Decimal Deg., Meters, String
Euler's Town,7.58857,47.559537,0, "Blah"
Faneuil Hall,-71.054773,42.360217,0
Yellowstone National Park,-110.588455,44.427963,0

Sau đó, trích xuất Phương thức cho phép bạn chỉ định những gì bạn muốn làm với thông tin tiêu đề (trong ví dụ này, chúng tôi chỉ đơn giản là mã hóa các dòng tiêu đề dựa trên dấu phẩy và trả lại như một danh sách nhưng có chỗ để làm nhiều hơn nữa).

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens

Đầu ra

['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']

Nếu

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens
2 chứa một tiêu đề khác, chỉ cần thay đổi
def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens
4. Trên hết, rõ ràng những gì
def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens
5 đang làm và chúng tôi tránh sự mơ hồ khi phải tìm ra hoặc nhận xét về lý do tại sao tác giả của câu trả lời được chấp nhận sử dụng
def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens
6 trong mã của mình.

Trong bài viết này sẽ xem cách bỏ qua một dòng trong một tệp trong Python. Có nhiều cách để làm điều đó. Trong bài viết này, chúng tôi sẽ thảo luận về hai cách tiếp cận.

1. Sử dụng phương thức readlines ()

Phương thức ReadLines () đọc một tệp và trả về một danh sách. Ở đây, mỗi mục của một danh sách chứa một dòng của tệp, tức là, danh sách [0] sẽ có dòng đầu tiên, danh sách [1] dòng thứ hai, v.v.readlines() method reads a file and returns a list. Here, each item of a list contains a line of the file, i.e., list[0] will have the first line, list[1] the second line, and so on.

Vì nó là một danh sách, chúng tôi có thể lặp lại nó. Khi số dòng hiện tại bằng số dòng mà chúng tôi muốn bỏ qua, chúng tôi bỏ qua dòng đó. Nếu không, chúng tôi xem xét nó.

Hãy xem xét ví dụ sau trong đó chúng tôi in tất cả các dòng, ngoại trừ bản mà chúng tôi muốn bỏ qua.

def skipLine(f, skip):
  lines = f.readlines()
  skip = skip - 1 #index of the list starts from 0

  for line_no, line in enumerate(lines):
    if line_no==skip:
      pass
    else:
      print(line, end="")

Hãy cùng thử mã trên bằng cách bỏ qua dòng đầu tiên của tệp mẫu.txt.sample.txt file.

sample.txt

This is a sample file.
Python is a very powerful programming language.
Let's see how to skip a line in Python.
It is very easy.
I love Python. It makes everything so fun.
try:
  f = open("sample.txt", "r")
  skipLine(f, 1) 
finally:
  f.close()

Hướng dẫn how do you skip the first line while reading a file in python? - làm thế nào để bạn bỏ qua dòng đầu tiên khi đọc tệp trong python?

Đầu ra

Python is a very powerful programming language.
Let's see how to skip a line in Python.
It is very easy.
I love Python. It makes everything so fun.

Bây giờ, hãy bỏ qua dòng thứ 3.rd line.

try:
  f = open("sample.txt", "r")
  skipLine(f, 3) 
finally:
  f.close()

Đầu ra

This is a sample file.
Python is a very powerful programming language.
It is very easy.
I love Python. It makes everything so fun.

Bây giờ, hãy bỏ qua dòng thứ 3.

Nếu bạn vượt qua một giá trị lớn hơn tổng số dòng hoặc nhỏ hơn 1, thì sẽ không có gì xảy ra.

2. Sử dụng phương thức readlines () và cắt giảm danh sáchreadlines() method returns a list, we can perform slicing to skip a specific line. Consider the following example.

def skipLineSlicing(f, skip):
  skip -= 1 #index of list starts from 0
  if skip < 0: # if the skip is negative, then don't make any changes in the list
    skip= 1
  lines = f.readlines()
  lines = lines[0:skip] + lines[skip+1:len(lines)]
  for line in lines:
    print(line, end="")

Vì phương thức Readlines () trả về một danh sách, chúng ta có thể thực hiện cắt lát để bỏ qua một dòng cụ thể. Xem xét các ví dụ sau.sample.txt file.

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens
0

Đầu ra

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens
1

Hướng dẫn how do you skip the first line while reading a file in python? - làm thế nào để bạn bỏ qua dòng đầu tiên khi đọc tệp trong python?

Bây giờ, hãy bỏ qua dòng thứ 3.

Làm thế nào để bạn bỏ qua một dòng khi mở một tệp trong Python?

Sử dụng Next () để đọc một tệp bắt đầu với dòng thứ hai Sử dụng Mở (tệp) để mở tệp.Gọi tiếp theo (Tệp) để bỏ qua dòng đầu tiên của tệp.Call next(file) to skip the first line of the file.

Làm cách nào để bỏ qua dòng đầu tiên của tệp văn bản?

Bạn có thể sử dụng P.Readline () hoặc Next (Readline) để bỏ qua một dòng, trước khi bạn lặp qua các dòng còn lại.Điều này sẽ đọc một dòng, và sau đó chỉ cần vứt nó đi.Lưu câu trả lời này.use p. readline() or next(readline) to skip a line, before you loop over the remaining lines. This will read a line, and then just throw it away. Save this answer.

Làm thế nào để bạn bỏ qua một dòng trong văn bản trong Python?

Làm thế nào để bỏ qua một dòng trong Python bằng cách sử dụng \ n ?..
Ký tự dòng mới của Python \ n chỉ ra phần cuối của một dòng văn bản ..
Hàm in tích hợp () tự động thêm một ký tự mới \ n ở cuối ..

Làm thế nào để bạn bỏ qua dòng đầu tiên trong một đường đọc?

Lệnh readlines () trả về một danh sách các chuỗi, với mỗi phần tử là một dòng duy nhất trong tệp, được phân tách bởi ký tự EOL.Vì đối tượng được trả về là một danh sách, chúng ta có thể sử dụng cắt python như trong bất kỳ danh sách nào khác.Ví dụ: bỏ qua dòng đầu tiên, chỉ cần bắt đầu sử dụng danh sách từ phần tử thứ hai.start using the list from the second element.