Python将文本与变量写入TXT文件报错求助
Hey there! Let's break down and fix the issue you're facing step by step.
What's Causing the Error?
The TypeError: write() takes exactly one argument (3 given) pops up because the file.write() method only accepts a single string argument, but you’re passing three separate values (like "Number Plate:", np, and "\n") each time you call it. Also, there’s a typo in your code: f.wrtie should be f.write—that would’ve caused another error once you fixed the first issue!
Solutions to Fix It
You need to combine your text and variables into one single string before passing it to write(). Here are a few clean, easy ways to do this:
1. Use F-Strings (Recommended for Python 3.6+)
F-strings let you embed variables directly into strings in a super readable way:
f = open("Output.txt", "a") f.write(f"Number Plate: {np}\n") f.write(f"Valid: {valid}\n") f.write(f"Speed: {speed}\n") f.write(f"Ticket: {ticket}\n") f.write(f"Ticket Price: {ticketprice}\n") f.write("\n") f.close()
2. String Concatenation
You can glue strings together with the + operator—just make sure non-string variables (like numbers) are converted to strings first with str():
f = open("Output.txt", "a") f.write("Number Plate: " + str(np) + "\n") f.write("Valid: " + str(valid) + "\n") f.write("Speed: " + str(speed) + "\n") f.write("Ticket: " + str(ticket) + "\n") f.write("Ticket Price: " + str(ticketprice) + "\n") f.write("\n") f.close()
3. Use str.format() (Great for Older Python Versions)
If you’re working with Python 3.5 or earlier, str.format() is a reliable option:
f = open("Output.txt", "a") f.write("Number Plate: {}\n".format(np)) f.write("Valid: {}\n".format(valid)) f.write("Speed: {}\n".format(speed)) f.write("Ticket: {}\n".format(ticket)) f.write("Ticket Price: {}\n".format(ticketprice)) f.write("\n") f.close()
Bonus: Use a Context Manager (Even Better!)
To avoid forgetting to close the file or running into unexpected errors, use a with statement—it automatically closes the file for you when you’re done:
with open("Output.txt", "a") as f: f.write(f"Number Plate: {np}\n") f.write(f"Valid: {valid}\n") f.write(f"Speed: {speed}\n") f.write(f"Ticket: {ticket}\n") f.write(f"Ticket Price: {ticketprice}\n") f.write("\n")
内容的提问来源于stack exchange,提问作者user9754923

