Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将我创建的索引写入Python文件_Python_Python 2.7 - Fatal编程技术网

如何将我创建的索引写入Python文件

如何将我创建的索引写入Python文件,python,python-2.7,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}

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

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.

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

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

Pickle并不是为了美观,而是为了将数据序列化到文件中,以便以后可以高效地对其进行反序列化。其他模块(如模块)旨在以良好的方式打印Python数据。但是,如果您的目标是以后能够对数据进行反序列化,那么您可以查看该格式及其特性

导入pprint >>>pp=pprint.预印机(缩进=4) >>>pp.pprint(myIndex) { '411)': {2173: 1}, '增广':{1350:1}, “自由格式”:{720:1}, '函数':{485:1831:11579:1}, '合并':{2047:1}, “理解”:{2396:1} >>>导入json >>>output=json.dumps(myIndex,sort_keys=True,indent=4,分隔符=(',',':')) >>>打印(输出) { "411)": { "2173": 1 }, “增广”:{ "1350": 1 }, “无格式”:{ "720": 1 }, “功能,”:{ "485": 1, "831": 1, "1579": 1 }, “合并”:{ "2047": 1 }, “理解”:{ "2396": 1 } } >>>myRecoveredIndex=json.loads(输出) >>>列表(myRecoveredIndex.keys()) [‘无格式’、‘合并’、‘功能’、‘理解’、‘扩充’、‘411’] >>> 如果您建议的格式确实重要,那么您可以根据您的格式自己编写文件。以下是如何做到这一点的建议:

打开(“myfile.txt”、“w”)作为fstream:
对于键,myIndex.items()中的数据:
write(“{}”:{!s}\n”.format(key,data))

indent=4是否表示单词前面的空格,例如XXXX“2173”:1?是:如果indent是非负整数或字符串,则JSON数组元素和对象成员将以该缩进级别打印出来。缩进级别为0、负或“”将仅插入换行符。无(默认值)选择最紧凑的表示形式。使用正整数缩进每个级别可以缩进那么多空格。如果缩进是一个字符串(如“\t”),则该字符串用于缩进每个级别。在版本3.2中更改:除了整数外,还允许缩进字符串。(因此indent=“\t”不适用于Python 2.7)感谢您的帮助。我很感激:)我也学到了更多关于PrettyPrinter的知识。@user2966953没问题,如果它解决了你的问题,也许可以接受这个答案?