Python读取文件数据时出现异常,硬编码数据可正常运行,寻求解决方法
Hey there! I’ve run into this exact problem before—let me break down what’s going wrong and how to fix it quickly.
The Root Cause
When you use file.readline(), it doesn’t just grab the text on the line—it also includes the newline character (\n) at the end of each line. For example, if your data.txt looks like this:
exampleusername examplepassword example@example.com 2018
Your username variable ends up being "exampleusername\n" instead of the clean "exampleusername" you hardcoded earlier. That extra newline throws off the website’s validation, which is why you’re seeing that error.
Quick Fixes
Here are a few straightforward ways to fix this:
Strip whitespace from each line
Use thestrip()method to remove newline characters, spaces, and tabs from the start/end of each read value:with open("data.txt", "r") as file: username = file.readline().strip() password = file.readline().strip() email = file.readline().strip() year = file.readline().strip()(I used a
withstatement here because it automatically closes the file for you—no need to rememberfile.close()!)Read all lines at once and clean them
If you prefer, you can read all lines in one go, then process them:with open("data.txt", "r") as file: # Read all lines, strip whitespace, and filter out any empty lines lines = [line.strip() for line in file if line.strip()] username, password, email, year = linesThis is handy if your file might have blank lines you want to skip.
Check what you’re actually reading
If you’re still stuck, print the raw values to see hidden characters. Userepr()to show exactly what’s in the variable:print(repr(username)) # Will show "exampleusername\n" if the newline is presentThis helps confirm if the newline is the culprit.
Bonus Tip
Make sure your data.txt doesn’t have any extra spaces or blank lines at the start/end—those can cause issues too. The strip() method takes care of most of that, but it’s good to double-check the file content.
内容的提问来源于stack exchange,提问作者neminem




