简体   繁体   English

在python中使用file.write()

[英]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? 由于某种原因,file.write()将仅接受1个字符串或变量,而我的问题有没有解决的办法?

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. 像这样,但是没有.write(),因为它不允许您这样做。

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. 例如, str(var)会将var转换为字符串类型。

You can simply use str(numApples) and so on in your case and append them using + (string concatenate) operator. 您可以简单地使用str(numApples)等,然后使用+ (字符串串联)运算符将其附加。 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. 在这里,您只有一个字符串参数,而不是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. 使用file.writelines ,它需要字符串的迭代,而不是单个字符串。

Or else use print(*args, file=) which takes anything and calls str() for you. 否则使用print(*args, file=)接受任何内容并为您调用str()。

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 '+' 使用str()使每个部分成为字符串,然后使用'+'进行连接
  2. Using str.format 使用str.format
  3. Using nice and concise old syntax: 使用简洁明了的旧语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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