Home >Backend Development >Python Tutorial >How to filter file content in python
In python, you can use the following methods to filter file content:
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]
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)
re
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!