Python 如何打印包含给定字符串的文件行

Python 如何打印包含给定字符串的文件行

在本文中,我们将展示如何使用Python打印出包含给定特定字符串的所有行。

假设我们已经拿到一个名为 ExampleTextFile.txt 的文本文件,其中包含一些随机文本。我们将从文本文件中返回包含给定特定字符串的行。

ExampleTextFile.txt

Good morning to TutorialsPoint
This is TutorialsPoint sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome to TutorialsPoint
Learn with a joy
Good morning to TutorialsPoint

步骤

以下是执行所需任务的算法/步骤:

  • 创建一个变量来存储文本文件的路径。

  • 输入字符串作为静态/动态输入并将其存储在一个变量中。

  • 使用 open() 函数(打开一个文件并返回一个文件对象作为结果)以只读模式打开文本文件,将文件名和模式作为参数传递给它(这里“ r ”表示只读模式)。

with open(inputFile, 'r') as filedata:
  • 使用for循环遍历文本文件的每一行

  • 使用if条件语句和“ in ”关键字,检查给定的字符串是否出现在上述行数据中。

in关键字用于确定一个值是否存在于序列中(列表、范围、字符串等)。

它也用于在for循环中迭代一个序列。

  • 如果在相应的行中找到给定的字符串,则打印该行。

  • 使用 close() 函数(用于关闭已打开的文件)关闭输入文件。

示例

以下程序逐行检查给定的字符串是否在文本文件的一行中找到,并在找到字符串时打印该行 –

# input text file
inputFile = "ExampleTextFile.txt"

# Enter the string
givenString = "to TutorialsPoint"
print('The following lines contain the string {', givenString, '}:')

# Opening the given file in read-only mode
with open(inputFile, 'r') as filedata:

   # Traverse in each line of the file

   for line in filedata:

      # Checking whether the given string is found in the line data

      if givenString in line:

         # Print the line, if the given string is found in the current line
         print(line)

# Closing the input file
filedata.close()

输出

执行上述程序后,将生成以下输出 –

The following lines contain the string { to TutorialsPoint }:
Good morning to TutorialsPoint
Welcome to TutorialsPoint
Good morning to TutorialsPoint

我们在这个程序中读取一个包含一些随机文本的文本文件。我们逐行读取文本文件,然后检查给定的字符串是否出现在该行数据中。如果存在,我们就打印该行的当前值(总行值)。

结论

我们学会了如何读取文件,逐行遍历文件,并获取本文中的所有行数据。一旦我们获取到它们,我们可以反转行,改变大小写,查找该行中的单词数,检查元音字母,检索行字符等。我们还学会了如何在文件中搜索字符串并打印相关行,这在日常应用程序中通常用于查找ID并打印该人员的所有信息。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程