【问题标题】:pickle.dump dumps nothing when appending to file附加到文件时,pickle.dump 不转储任何内容
【发布时间】:2017-10-15 22:49:13
【问题描述】:

用户可能会给出一堆 url 作为命令行参数。过去给出的所有 URL 都使用 pickle 进行序列化。该脚本检查所有给定的 URL,如果它们是唯一的,则将它们序列化并附加到文件中。至少这是应该发生的事情。没有附加任何内容。但是,当我以写入模式打开文件时,会写入新的唯一 URL。那么给了什么?代码是:

def get_new_urls():
    if(len(urls.URLs) != 0): # check if empty
        with open(urlFile, 'rb') as f:
            try:
                cereal = pickle.load(f)
                print(cereal)
                toDump = []
                for arg in urls.URLs:
                    if (arg in cereal):
                        print("Duplicate URL {0} given, ignoring it.".format(arg))
                    else:
                        toDump.append(arg)
            except Exception as e: 
                print("Holy bleep something went wrong: {0}".format(e))
            return(toDump)

urlsToDump = get_new_urls() 
print(urlsToDump)
# TODO: append new URLs
if(urlsToDump):
    with open(urlFile, 'ab') as f:
        pickle.dump(urlsToDump, f)

# TODO check HTML of each page against the serialized copy
with open(urlFile, 'rb') as f:
    try:
        cereal = pickle.load(f)
        print(cereal)
    except EOFError: # your URL file is empty, bruh
        pass

【问题讨论】:

  • 虽然创意很好,但请记住,这是一个适合儿童的网站;-(
  • "ain't dumpin' no thing" 只是错误

标签: python file pickle


【解决方案1】:

Pickle 以特殊格式写出您提供的数据,例如它会将一些标头/元数据/等写入您提供的文件。

它不打算以这种方式工作;连接两个泡菜文件并没有真正的意义。要实现数据的串联,您需要首先将文件中的任何内容读入您的urlsToDump,然后使用任何新数据更新您的urlsToDump,最后再次将其转储出来(覆盖整个文件,不附加)。

【讨论】:

    【解决方案2】:

    之后

    with open(urlFile, 'rb') as f:
    

    您需要一个 while 循环,以反复从文件中提取(反复读取)直到遇到 EOF。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多