Python脚本:输入内容在TXT文件中检索的代码故障求助
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:
withstatement: This ensures the file is closed automatically, even if there's no match or an error occurs. No need to callfile.close()manually!line.strip(): Cleans up each line by removing leading/trailing spaces, tabs, and newlines, so yourstartswithcheck works as expected.breakstatement: 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

