[英]Python f.write() is not taking more arguments
我有這樣的python代碼
f=open('nv.csv','a+')
a=10+3
b=3+12
c=3+13
f.write(a,b,c)
這將輸出返回為
f.write(a,b,c)
TypeError: function takes exactly 1 argument (3 given)
請幫我解決這個問題。 我希望將每個數據輸入到我的文件中。
file.write
接受一個參數,一個字符串。 您必須加入您的值,然后寫入該文件。 最后,不要忘記關閉您的文件:
f=open('nv.csv','a+')
a=10+3
b=3+12
c=3+13
f.write("{} {} {}\n".format(a, b, c))
f.close()
如果您稍后要使用多個值,則應使用列表:
s = [13, 15, 16, 45, 10, 20]
f.write(' '.join(map(str, s)))
f.close()
編輯:
關於你最近的評論,你有兩個選擇。
創建初始字典:
s = {"a":13, "b":15, "c" = 16}
for a, b in s.items():
f.write("{} {}\n".format(a, b))
f.close()
或者,使用帶有列表的globals
:
s = [13, 15, 16, 45, 10, 20]
final_data = {a:b for a, b in globals().items() if b in s}
for a, b in final_data.items():
f.write("{} {}\n".format(a, b))
f.close()
使用f.writelines()
: https : f.writelines()
f.writelines([a,b,c])
沒有添加行分隔符。
如果你想要一個特殊的分隔符,使用"separator".join([str(i) for i in [a,b,c]])
並通過f.write()
將其寫入文件
所有以前都是有效的,我會盡力完成它們
with open('nv.csv','a+') as f:
a = 10 + 3
b = 3 + 12
c = 3 + 13
f.write('{}\n'.format( ','.join(map(str, (a, b, c))) )
f.write()
只接受一個參數並將其寫入您的文件。 如果要編寫多個組件,可以使用f.writelines([a,b,c])
。 此外,您只能將字符串寫入文件,因此請確保為所有變量執行str(*)
。
建議的所有答案都很好。 如果你想讓它更具可讀性和整潔性,你也可以這樣做:
f.write("{a},{b},{c}".format(a=a, b=b, c=c)
您可以使用%運算符
請注意,替換變量x,y,z都在括號中,這意味着它們是傳遞給%運算符的單個元組。
a=10+3
b=3+12
c=3+13
f.write("%s %s %s" % (a, b, c))
f.close()
這是一個可以在線執行的示例 。
代碼完美無缺。
輸出為: 13 15 16
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.