Home >Backend Development >Python Tutorial >How to filter file content in python

How to filter file content in python

王林
王林forward
2024-03-01 21:04:13979browse

How to filter file content in python

In python, you can use the following methods to filter file content:

  1. Use the readlines() method to read all lines of the file and use conditional statements to filter the content. For example, to filter out lines containing a specific keyword:
with open('file.txt', 'r') as file:
lines = file.readlines()
filtered_lines = [line for line in lines if 'keyWord' in line]
  1. Use a for loop to read the file line by line, and then use conditional statements to filter the content. For example, to filter out lines longer than 10:
with open('file.txt', 'r') as file:
filtered_lines = []
for line in file:
if len(line) > 10:
filtered_lines.append(line)
  1. Use regular expressions modulere to match and filter content. For example, to filter out rows matching a specific pattern:
import re

with open('file.txt', 'r') as file:
lines = file.readlines()
pattern = r'^[A-Za-z]+\d+'
filtered_lines = [line for line in lines if re.match(pattern, line)]

The above is the detailed content of How to filter file content in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete