2

我是一名编程初学者,并决定自学 Python。几天后,我决定编写一小段代码。我很简单:

  • 今天的日期
  • 我所在的页面(我在看书)
  • 我感觉如何
  • 然后我将数据添加到文件中。每次我启动程序时,它都会在文件中添加一行新数据
  • 然后我提取数据以制作列表列表。

事实是,我想重新编写我的程序以腌制一个列表,然后取消腌制文件。但是,由于我正在处理我无法处理的错误,我真的很想了解如何解决这个问题。因此,我希望你能帮助我:)

在过去的几个小时里,我一直在努力解决这个显然是一个简单而愚蠢的问题。虽然我没有找到解决方案。这是错误和代码:

错误:

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

代码:

import pickle
import datetime

def SaveData(datatosave):
    with open('journey.txt', 'wb') as thefile:
        my_pickler = pickle.Pickler(thefile)
        my_pickler.dump(datatosave)
        thefile.close()

todaylist = []
today = datetime.date.today()
todaylist.append(today)

page = input('Page Number?\n')
feel = input('How do you feel?\n')

todaysline = today.strftime('%d, %b %Y') + "; " + page + "; " + feel + "\n"

print('Thanks and Good Bye!')

SaveData(todaysline)

print('let\'s make a list now...')

thefile = open('journey.txt','rb')
thelist = [line.split(';') for line in thefile.readlines()]
thefile.close()

print(thelist)

感谢战利品!

4

2 回答 2

1

好的,所以这里有几件事要评论:

  1. 使用with语句时,不必显式关闭文件。Python 将在块的末尾with(第 8 行)为您执行此操作。

  2. 你什么都不用todayList。您创建它,添加一个元素,然后丢弃它。所以它可能没用:)

  3. 你为什么要腌制字符串对象?如果您有字符串,只需将它们按原样写入文件即可。

  4. 如果您在写入时腌制数据,则必须在读取时取消腌制它。您不应该编写腌制数据,然后将文件作为纯文本文件读取。

  5. 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(';'))
于 2013-08-17T11:23:28.973 回答
0

你确定你发布了正确的代码吗?如果您在打开文件时错过了“b”,则可能会发生该错误

例如。

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")
... 
>>> 
于 2013-08-17T11:35:09.223 回答