[英]Problems with writing and reading files in python
我需要在一個文本文件中寫入和讀取多個變量
myfile = open ("bob.txt","w")
myfile.write(user1strength)
myfile.write("\n")
myfile.write(user1skill)
myfile.write("\n")
myfile.write(user2strength)
myfile.write("\n")
myfile.write(user2skill)
myfile.close()
目前出現此錯誤:
Traceback (most recent call last):
File "D:\\python\\project2\\project2.py", line 70, in <module>
myfile.write(user1strength)
TypeError: must be str, not float
write
接受字符串。 因此,您可以構造一個字符串,然后一次將其全部傳遞。
myfile = open ("bob.txt","w")
myfile.write('\n{}\n{}\n{}'.format(user1strength, user2strength, user2skill))
myfile.close()
另外,如果您的python支持with
,則可以執行以下操作:
with open("bob.txt", "w") as myfile:
myfile.write('\n{}\n{}\n{}'.format(user1strength, user2strength, user2skill))
# code continues, file is closed properly here
如果您使用的是python3,請改用print函數。
with open("bob.txt", "w") as myfile:
print(user1strength, file=myfile)
print(user1skill, file=myfile)
print(user2strength, file=myfile)
print(user2skill, file=myfile)
打印功能將為您轉換為str
,並自動為您添加\\n
。 我還使用了with
塊,它將自動為您關閉文件。
如果您使用的是python2.6或python2.7,則可以使用from __future__ import print_function
訪問打印功能。
您的變量之一可能不是字符串類型。 您只能將字符串寫入文件。
您可以執行以下操作:
# this will make every variable a string
myfile = open ("bob.txt","w")
myfile.write(str(user1strength))
myfile.write("\n")
myfile.write(str(user1skill))
myfile.write("\n")
myfile.write(str(user2strength))
myfile.write("\n")
myfile.write(str(user2skill))
myfile.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.