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[]

Đầ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 

Bài Viết Liên Quan

Chủ Đề