使用python在文件中写入数据

时间:2019-02-27 14:00:41

标签: python python-3.x

我是编程新手。刚刚在Python中为初学者买了一本书。在其中,我得到了以下代码:

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 ()

根据预定的书,但是我得到了这个错误:

TypeError: a bytes-like object is required, not 'str'

我不知道如何解决它,本书也没有对此进行解释。

2 个答案:

答案 0 :(得分:1)

我们来看一下:

name = input("Your name: ")
email = input("Your email: ")

如前所述,需要用引号引起来。

outputString = name + "|" + email + "|" +  favoriteband 

outputString+之前缺少email

最后,我们需要重写您的文件管理:

with open(fileName, "a") as file:
  file.write (outputString) 
  print (outputString , " saved in ", fileName) 

将其写为with语句可确保它将关闭。使用open(..., "a")以“追加”模式打开文件,并允许您将多个字符串写入同名文件。

最后,如果我可以编辑的话,到目前为止,我还不喜欢这本书。

编辑:这是带有修复程序的整个代码,希望能带您到达那里。

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) 

您可以验证它是否可以使用:

with open(fileName, "r") as file:
  print(file.read())

答案 1 :(得分:0)

我做了一些编辑(用引号引起来,并缺少+):

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()

由于以二进制模式编写,因此出现了该错误,因此b中的wb

file = open(fileName, "wb")

尝试以下方法:

file = open(fileName, "w")