如何在Python中将我创建的索引编写到文件中

时间:2013-11-12 20:24:09

标签: python python-2.7

我想知道如何将以下索引写入文件。下面的索引是从我创建的函数返回的。

myIndex = {'incorporating': {2047: 1}, 'understand': {2396: 1}, 'format-free': {720: 1}, 'function,': {1579: 1, 485: 1, 831: 1}, '411)': {2173: 1}, 'augmented': {1350: 1}}

我想要这样的东西出现在输出文件中。

'incorporating': {2047: 1} 
'understand': {2396: 1}
'format-free': {720: 1}
'function,': {1579: 1, 485: 1, 831: 1}, '411)': {2173: 1}
'augmented': {1350: 1}

这是我做过的代码。我试图使用writeLine,但我的文件中的输出搞砸了。所以我寻找其他方法,如泡菜。

def ToFile(self):
indList = myIndex.constructIndex()  # a function to get the index above
filename = "myfile.txt"
outfile = open(filename, 'wb')
pickle.dump(indexList, outfile)

outfile.close()

我查看了我的文件,但我得到的是:

ssS'incorporating'
p8317
(dp8318
I2047
I1
ssS'understand'
p8319
(dp8320
I2396
I1
ssS'format-free'
p8321
(dp8322
I720
I1
ssS'function,'
p8323
(dp8324
I1579
I1
sI485
I1
sI831
I1
ssS'411)'
p8325 
(dp8326
I2173
I1
ssS'augmented'
p8327
(dp8328
I1350
I1
ss.

2 个答案:

答案 0 :(得分:2)

您应该直接尝试写入文件:

for key in myIndex:
    outfile.write("'" + key + "': " + str(myIndex[key]) + "\n")

答案 1 :(得分:2)

Pickle不是很好,而是将数据序列化到一个文件,以便以后可以有效地反序列化它。其他模块,如PrettyPrint模块,旨在以一种很好的方式打印出Python数据。但是,如果您的目标是以后能够反序列化数据,则可以查看JSON格式及其Python module

>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(myIndex)
{   '411)': {2173: 1},
    'augmented': {1350: 1},
    'format-free': {720: 1},
    'function,': {485: 1, 831: 1, 1579: 1},
    'incorporating': {2047: 1},
    'understand': {2396: 1}}
>>> import json
>>> output = json.dumps(myIndex,sort_keys=True,indent=4, separators=(',', ': '))
>>> print(output)
{
    "411)": {
        "2173": 1
    },
    "augmented": {
        "1350": 1
    },
    "format-free": {
        "720": 1
    },
    "function,": {
        "485": 1,
        "831": 1,
        "1579": 1
    },
    "incorporating": {
        "2047": 1
    },
    "understand": {
        "2396": 1
    }
}
>>> myRecoveredIndex = json.loads(output)
>>> list(myRecoveredIndex.keys())
['format-free', 'incorporating', 'function,', 'understand', 'augmented', '411)']
>>> 

如果您建议的格式很重要,则可以根据您的格式自行编写文件。以下是如何做到这一点的建议:

with open("myfile.txt", "w") as fstream:
    for key, data in myIndex.items():
        fstream.write("'{}': {!s}\n".format(key, data))