如何处理 python 中的文本文件

How to handle text file in python

我有一个名为 words.txt 的文件,其中包含字典单词。我调用这个文件并要求用户输入一个词。然后尝试找出这个词是否存在于这个文件中如果是 print True else 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 文件在一行中包含每个字母,然后在第二行包含新字母。

使用这一行解决方案:

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

这个函数应该做到:

def searchWord(wordtofind):
    with open('words.txt', 'r') as words:
        for word in words:
            if wordtofind == word.strip():
                return True
    return False

您只需将 .read() 添加到您启动的文件 class 中。

像这样:

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

先读file,再用snake_case https://www.python.org/dev/peps/pep-0008/

user_word  = input("Type a Word:")
with open('words.txt') as f:
    content = f.read()
    if user_word in content:
        print(True)
    else:
        print('Word not found')