尝试在单独的文本文件中查找单词



我正在研究如何在一个单独的文本文件中找到一个单词。


我正在使用Python 3.x,我试图使服务器和客户端线程,客户端应该输入一个词。
然后服务器应该在给我的文本文件列表中找到单词


我该如何在文件中搜索单词呢?
我应该导入它与头或有不同的方法,我应该使用?

您可以尝试这样做:

with open(r"C:Pathtofile.txt", 'r') as file:
content = file.read()
if ("my word" in content):
print("Your string is in the file")
else:
print("String not found")

解释


open内置函数是这样使用的:

file = open(r"C:\Yourpath{file_name}.{file_extension}", mode_for_opening_the_file)

默认模式为'r',表示读取文件。


您可以通过多种方式处理文件,其中最常用的两种是:

  1. with关键字
  2. 文件对象对变量
  3. 的简单赋值

第一个例子:

with open(r"MyFile.json", 'r') as file:
print(file.read())

第二个例子:

file = open(r"MyFile.json", 'w+')
file.write("Hello World")
file.close() # The with method automatically close the file, saving all the changes

更多信息


如果您想了解更多关于使用python打开文件的信息,请查看:

  • 读写文件
  • 写入现有文件
  • 读取文本文件

最新更新