Hướng dẫn python skip code - mã bỏ qua python

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. 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. 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 file.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.rd line.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.rd line.rd line.

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

Bây giờ, hãy bỏ qua dòng thứ 3.readlines[] 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ủ Đề