创建字典以写入fi

2024-04-25 16:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更改文件的写入格式。该文件以通用文件格式编写。我将头文件放入文件中并编写它,以便将来通过使用pandas字典或xarray datarray就可以被另一个程序读取。为了做到这一点,我正在尝试使文件中的列比现在的列更加独立。我有以下代码:

def cvrtpa(fle,separation_character,(labels)):
    import numpy as np
    import pandas as pd
    labels[-1]=labels[-1]+'\n'
    flabels=labels
    finlabel = np.array([flabel + separation_character for flabel in flabels])
    infile=open(fle,'r')
    templines=infile.readlines()
    vardict = {} #dict version
    for i in finlabel:
        for j in range(len(templines)):
            split=templines[j]            
            x = split.split()
            vardict.setdefault(finlabel[i],[]).append(x)
    infile.close()
    outfile=open(fle, 'w')
    outfile.write(finlabel)
    outfile.write(temp)
    outfile.close()
    mfile=open(fle,'r')
    data=mfile.readlines()
    return data

fl='.../Summer 2016/Data/Test/Test'
label=['Year','Month','Day','Hour','Minute','Precipitation']
xx=cvrtpa(fl,'',label)

我对字典不太熟悉,所以很难写出我的代码。我知道可能有不一致/错误。你知道吗


Tags: 文件代码inpandasforlabels字典open
1条回答
网友
1楼 · 发布于 2024-04-25 16:35:21
import json

# Create some random data structure
animals = zip(['dogs', 'cats', 'mice'], [124156, 858532, 812885])
data = {k:{v: {k: [v, v, v, k, v, {k: [k, k, k, k]}]}} for k, v in animals}

# Create a new file, dump the data to it
with open('filename.ext', 'w+') as file:
    json.dump(data, file, indent=4, sort_keys=False)

# Open the same file, load it back as a new variable
with open('filename.ext') as file:
    new_dictionary = json.load(file)

# Make some changes to the dict
new_dictionary['new_key'] = 'hello python'

# Open the file back up again and rewrite the new data
with open('filename.ext', 'w+') as file:
    json.dump(new_dictionary, file, indent=4)

相关问题 更多 >