0

Working on outputting text and variables to a .txt file through python. And it doesn't work.

f=open("Output.txt", "a")
f.write("Number Plate:", np ,"\n")
f.write("Valid:", valid ,"\n")
f.write("Speed:", speed ,"\n")
f.write("Ticket:", ticket ,"\n")
f.wrtie("Ticket Price:", ticketprice ,"\n")
f.write("\n")
f.close()

This is the error that is given when i run it.

f.write("Number Plate:", np ,"\n")
TypeError: write() takes exactly one argument (3 given)

Any help is greatly appreciated

3
  • In the line, f.write("Number Plate:", np ,"\n") what is np ? Commented May 23, 2018 at 8:05
  • Error message should be clear enough for you to understand what is wrong with the code. Commented May 23, 2018 at 8:06
  • 1
    Please go through the syntax for write function at docs.python.org/3/tutorial/inputoutput.html. Commented May 23, 2018 at 8:11

3 Answers 3

1

Try using str.format.

Ex:

f=open("Output.txt", "a")
f.write("Number Plate: {0}".format(np))
f.write("Valid: {0}".format(valid ))
f.write("Speed: {0}".format(speed ))
f.write("Ticket: {0}".format(ticket ))
f.write("Ticket Price: {0}".format(ticketprice ))
f.write("\n")
f.close()

Note: f.write takes only a single argument, You are trying to pass 3("Number Plate:", np ,"\n")

Sign up to request clarification or add additional context in comments.

3 Comments

You forgot {} in your f.write("Valid: {}".format(valid ))
@zvone. Thanks :)
And it would be better to either use with open()... or to put the whole file usage in try: ... finally: f.close() ;)
0

You can try like this:

with open("Output.txt", "a") as f:
    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")

Explanation:

If you use with open.... there is no need to explicitly specify the f.close(). And also in f.write() using string concatenation + you can get the required one.

1 Comment

@dominicXD hough: Is this what you are expecting ?
0

You can simply use str() function

The str() function is meant to return representations of values which are fairly human-readable.

And your valid code will be like-

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.wrtie("Ticket Price:" + str(ticketprice) + "\n")
f.write("\n")
f.close()

your code giving Error, TypeError: write() takes exactly one argument (3 given)

because-

write() method takes only 1 argument, but you are providing 3 argument

1) "Number Plate:" , 2) np and 3) "\n"

Comments