简体   繁体   English

在 Python 3.3 中写入文件

[英]File writing in Python 3.3

Can anyone give me advice on writing in files.谁能给我写文件的建议。 This is in python 3.3.这是在python 3.3中。 This error message just keeps on popping up.此错误消息不断弹出。

Traceback (most recent call last):Line 28, in file.write(name_1,"and",name_2,"have a",loveness_2,"percent chance of falling in love") TypeError: write() takes exactly 1 argument (6 given)回溯(最近一次通话):第 28 行,在 file.write(name_1,"and",name_2,"have a",loveness_2,"percent chance of in love") 类型错误:write() 只需要 1 个参数( 6 给)

And my code is this:我的代码是这样的:

  if vowels_1 > vowels_2:
      loveness = vowels_2/vowels_1
      loveness_2 = loveness * 100
      print("It is ",loveness_2,"% possible of you falling in love")
      print("*********************************************")
      file.write("*********************************************")
      file.write(name_1,"and",name_2,"have a",loveness_2,"percent chance of 
      falling in love")

file.write is not the same as print ; file.writeprint as the error says, it only takes a single argument.正如错误所说,它只需要一个参数。 You need to compose your string before passing it to that call.您需要在将字符串传递给该调用之前编写字符串。

One way to do that is with string formatting:一种方法是使用字符串格式:

line = "{} and {} have a {} percent chance of falling in love".format(name_1, name_2, loveness_2)
file.write(line)

A comma separates arguments, so the interpreter thinks you're giving a bunch of arguments here.逗号分隔参数,因此解释器认为您在这里给出了一堆参数。 If you want to do a string concatenation, use '+'.如果要进行字符串连接,请使用“+”。

print('a' + 'b')
>>> 'ab'

A more pythonic way would be to use .format()一种更 Pythonic 的方式是使用 .format()

print('{} some text {}'.format('foo', 'bar')
>>>'foo some text bar'

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

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