[英]writing data in file using python
I am new in programming. 我是编程新手。 Just bought a book for beginners in
Python
. 刚用
Python
买了一本书给初学者。 In it I got this code: 在其中我得到了以下代码:
name = input("name")
email = input("whats ure email:)
favoriteband = input("ure fav band")
outputString = name + "|" email + "|" + favoriteband
fileName = name + ".txt"
file = open(fileName, "wb")
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close ()
According to book its fine but I got this error: 根据书的罚款,但我得到这个错误:
TypeError: a bytes-like object is required, not 'str'
I got no clue how to fix it and book isn't explaining this as well. 我不知道如何解决它,本书也没有对此进行解释。
Let's go through this: 让我们来看一下:
name = input("Your name: ")
email = input("Your email: ")
The close quotes are needed as has been pointed out. 正如已经指出的那样,需要用引号引起来。
outputString = name + "|" + email + "|" + favoriteband
outputString
was missing a +
before email
outputString
在email
前缺少+
Finally, we need to rewrite you file management: 最后,我们需要重写您的文件管理:
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
Writing this as a with
statement guarantees it will close. 将其编写为
with
语句可确保将其关闭。 Using open(..., "a")
opens the file in "append" mode and lets you write multiple strings to a file of the same name. 使用
open(..., "a")
以“追加”模式打开文件,并允许您将多个字符串写入同名文件。
Finally, if I can editorialize, I am not a fan of this book so far. 最后,如果我可以编辑的话,到目前为止,我还不喜欢这本书。
Edit: here is the whole code with fixes, in hopes of getting you there. 编辑:这是带有修复程序的整个代码,希望能带您到那里。
name = input("name")
email = input("whats ure email:")
favoriteband = input("ure fav band")
outputString = name + "|" + email + "|" + favoriteband
fileName = name + ".txt"
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
You can verify it works with: 您可以验证它可用于:
with open(fileName, "r") as file:
print(file.read())
I did some editing (closing quotes and a missing +
): 我做了一些编辑(右引号和缺少的
+
):
name = input("name:")
email = input("whats ure email:")
favoriteband = input("ure fav band:")
outputString = name + " | " + email + " | " + favoriteband
fileName = name + ".txt"
file = open(fileName, "w") #opened in write mode but not in binary
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close()
You're getting that error because you're writing in binary mode, hence the b
in wb
for 你得到的错误,因为你以二进制方式写入,因此
b
在wb
为
file = open(fileName, "wb")
Try this instead : 试试这个代替:
file = open(fileName, "w")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.