python - 使用 Python cPickle 从文件中读取数据

标签 python readfile pickle

问题是我只能读取 InputFile.bak 文件的第一行。如何使用cPickle从文件中读取所有信息。

输入文件-InputFile.bak

 (dp1
S'Here we go'
p2
(cdatetime
date
p3
(S'\x07\xdc\x0c\x0c'
tRp4
cdatetime
time
p5
(S'\x0c\x0c\x00\x00\x00\x00'
tRp6
tp7
s.(dp1
S'Here we go'
p2
(cdatetime
date
p3
(S'\x07\xdc\x0c\x0c'
tRp4
cdatetime
time
p5
(S'\x0c\x0c\x00\x00\x00\x00'
tRp6
tp7
s.(dp1
S'Here we go'
p2
(cdatetime
date
p3
(S'\x07\xdc\x0c\x0c'
tRp4
cdatetime
time
p5
(S'\x0c\x0c\x00\x00\x00\x00'
tRp6
tp7
sS'Google Searching'
p8
(g3
(S'\x07\xdc\x0c\x0b'
tRp9
g5
(S'\x01\x17\x00\x00\x00\x00'
tRp10
tp11
s.

源代码

import time
import datetime
import cPickle
import os
from sys import exit


def read_file():
    if os.path.exists('InputFile.bak'):
        try:
            fname = open('InputFile.bak', 'rb')
            file_src = cPickle.Unpickler(fname)
            item_name = file_src.load()
            for k, v in item_name.iteritems():
                print v[0], "\t", v[1],"\t", k
        finally:
            fname.close()
    else:
        item_name = {}

if __name__ == '__main__':
    read_file()

非常感谢。

最佳答案

您可以使用循环来获取所有记录。

def read_file():
    if os.path.exists('InputFile.bak'):
        # try:
        with open('InputFile.bak', 'rb') as fname:
            while True:
                try:
                    item_name = cPickle.load(fname)
                    for k, v in item_name.iteritems():
                        print v[0], "\t", v[1],"\t", k
                except EOFError:
                    break
    else:
        item_name = {}

if __name__ == '__main__':
    read_file()

关于python - 使用 Python cPickle 从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23147701/

相关文章:

c - 从文本文件中随机配对团队两次

python - 在 Linux 系统上存储 Python 数据

python - Pickle 一个对象作为其父类的实例?

python - 害怕 "not the same object error" pickle 一个 queryset.query 对象

Python 图形库

python - 我无法让 celery 正常工作(aws elasticbeanstalk)

java - 读取包含名称和数字混合的文件并将它们放入不同的数组中

python - 使用 python 从多个 xml 文件中提取数据

python - 使用 Pyspark-SQL 与 Pyspark 使用 Delta 格式查询表有什么区别?

python - 如何按时间读取日志文件并提取不包含数据信息的特定行