You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本:输入内容在TXT文件中检索的代码故障求助

Fixing Your Discord Name Checker Script

Hey there! Let's walk through the issues in your code and get it working properly.

First, let's break down what's going wrong with the original script:

  • Useless line with a typo: The line line.strip().split('/n') doesn't do anything useful. You used a forward slash (/) instead of a backslash (\) for the newline character, and even if fixed, splitting a single line on newlines isn't necessary here—plus you didn't save the result of the split, so it's just discarded.

  • Uncleaned line data: When reading lines from the file, each line includes a trailing newline character (\n). If you don't remove this, line.startswith(discordname) might fail because the newline is part of the line string.

  • File not closed on no match: You only close the file if you find a matching name. If the name isn't present, the file stays open, which is poor practice.

  • Loop keeps running after match: Once you find a match, you close the file but don't exit the loop—this can cause unexpected behavior with remaining iterations.

Here's the fixed version of your code:

discordname = input("What's your discord name?: ")

# Use a 'with' statement to automatically close the file when done
with open('rtf.txt', 'r') as file:
    for line in file:
        # Remove leading/trailing whitespace (including newlines) from the line
        cleaned_line = line.strip()
        # Check if the cleaned line starts with the Discord name
        if cleaned_line.startswith(discordname):
            print("works")
            break  # Stop checking further lines once we find a match

Key Changes Explained:

  1. with statement: This ensures the file is closed automatically, even if there's no match or an error occurs. No need to call file.close() manually!
  2. line.strip(): Cleans up each line by removing leading/trailing spaces, tabs, and newlines, so your startswith check works as expected.
  3. break statement: Exits the loop immediately after finding a match—no need to waste time checking other lines.

If you want to handle the case where the name isn't found, you can add an else block to the loop (this runs only if the loop completes without hitting break):

discordname = input("What's your discord name?: ")

with open('rtf.txt', 'r') as file:
    for line in file:
        cleaned_line = line.strip()
        if cleaned_line.startswith(discordname):
            print("works")
            break
    else:
        print("Sorry, that Discord name isn't in the file.")

That should get your script working smoothly!

内容的提问来源于stack exchange,提问作者user3513715

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:19:54