简体   繁体   中英

Using file.write() in python

I just had a quick question that keeps breaking my program. For some reason file.write() will only take in 1 string or variable and my question is there any way around this?

For example Im asking if it is possible to write multiple variables or strings to a file at once. Like this but without .write() because it doesn't allow you to.

file.write("apples: ", numApples, "\n oranges: ", numOranges)

Any help or suggestions are welcome!

The best answer I thought of right now is to make it all a string then send it to the file.

You can convert all the arguments to string and append them together.

For example, str(var) will convert var to string type.

You can simply use str(numApples) and so on in your case and append them using + (string concatenate) operator. The modified code will look like

file.write("apples: " + str(numApples) + "\\n oranges: " + str(numOranges))

Here you have just one string argument instead of 4.

you could also use format - :

file.write("apples: {0}\n oranges: {1}".format(numApples, numOranges) )

This gives you the flexibility to add formatting to the numbers, which you don't have with the the simple string concatenation solution.

Use file.writelines , which takes an iterable of strings, rather than a single string.

Or else use print(*args, file=) which takes anything and calls str() for you.

You need to make one arguemnt from your strings, there are few ways to do that:

  1. make each part a string using str(), then concatenate using a '+'
  2. Using str.format
  3. Using nice and concise old syntax:

     file.write("apples: %s\\noranges:%s" % (numApples, numOranges)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM