Python:data-to-file然后data-to-list-TypeError:必须是str,而不是bytes
我是一名编程初学者,决定自学Python。几天后,我决定编写一段代码。我很简单:Python:data-to-file然后data-to-list-TypeError:必须是str,而不是bytes,python,string,byte,pickle,Python,String,Byte,Pickle,我是一名编程初学者,决定自学Python。几天后,我决定编写一段代码。我很简单: 今天的日期 我在的页面(我正在看书) 我的感觉 然后我将数据添加到一个文件中。每次我启动程序时,它都会在文件中添加一行新数据 然后我提取数据,制作一个列表 事实是,我想重新编写我的程序,以便pickle一个列表,然后取消pickle文件。然而,由于我正在处理一个我无法处理的错误,我真的很想知道如何解决这个问题。因此,我希望你能帮助我:) 在过去的几个小时里,我一直在努力解决这个看似简单又愚蠢的问题。虽然我没有找
- 今天的日期
- 我在的页面(我正在看书)
- 我的感觉
- 然后我将数据添加到一个文件中。每次我启动程序时,它都会在文件中添加一行新数据
- 然后我提取数据,制作一个列表
Traceback (most recent call last):
File "dailyshot.py", line 25, in <module>
SaveData(todaysline)
File "dailyshot.py", line 11, in SaveData
mon_pickler.dump(datatosave)
TypeError: must be str, not bytes
谢谢你 好的,这里有几点要评论:
with
语句时,不必显式关闭文件。Python将在和
块(第8行)的末尾为您完成这项工作todayList
进行任何操作。创建它,添加一个元素,然后丢弃它。所以它可能没用:)a
进行追加当您刚刚将项目添加到文件中时,w
将覆盖整个文件import datetime
def save(data):
with open('journey.txt', 'a') as f:
f.write(data + '\n')
today = datetime.date.today()
page = input('Page Number: ')
feel = input('How do you feel: ')
todaysline = ';'.join([today.strftime('%d, %b %Y'), page, feel])
print('Thanks and Good Bye!')
save(todaysline)
print('let\'s make a list now...')
with open('journey.txt','r') as f:
for line in f:
print(line.strip().split(';'))
你确定你发布了正确的代码吗?如果在打开文件时遗漏了“b”,则可能会发生此错误 例如
谢谢你,维克多。关于您的代码,第22行似乎不起作用。我觉得好像少了点什么不?但是,有没有一种方法可以让我的代码通过修复这个“必须是str,而不是bytes”的错误来工作呢?这个错误乍一看并没有那么复杂。。。然而,我找不到如何修复它。我想知道我在这里没有学到什么:)我把它改了一点,现在是哪一行?你使用的是什么版本的python?很好的解释,完整的代码!谢谢你的时间:)1)是一个很好的提醒,谢谢/2):p/3+4)明白了5)这是我不知道的!是的,这是正确的密码。我不应该用腌菜,除非我需要解腌菜。
import datetime
def save(data):
with open('journey.txt', 'a') as f:
f.write(data + '\n')
today = datetime.date.today()
page = input('Page Number: ')
feel = input('How do you feel: ')
todaysline = ';'.join([today.strftime('%d, %b %Y'), page, feel])
print('Thanks and Good Bye!')
save(todaysline)
print('let\'s make a list now...')
with open('journey.txt','r') as f:
for line in f:
print(line.strip().split(';'))
with open('journey.txt', 'w') as thefile:
>>> with open('journey.txt', 'w') as thefile:
... pickler = pickle.Pickler(thefile)
... pickler.dump("some string")
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: must be str, not bytes
>>> with open('journey.txt', 'wb') as thefile:
... pickler = pickle.Pickler(thefile)
... pickler.dump("some string")
...
>>>