首页 > 解决方案 > 如何在python中处理文本文件

问题描述

我有一个文件名,称为words.txt其中包含字典单词。我调用这个文件并要求用户输入一个单词。然后尝试找出这个词是否存在于这个文件中,如果是,则打印True其他Word not found

wordByuser  = input("Type a Word:")
file = open('words.txt', 'r')
    
if wordByuser in file: #or if wordByuser==file:
    print("true")
else:
    print("No word found")

words.txt 文件在一行中包含每个字母,然后在第二行中包含新字母。

标签: pythondata-extraction

解决方案


使用这一行解决方案:

lines = file.read().splitlines()
if wordByuser in lines:
    ....

推荐阅读