简体   繁体   English

从字典创建.txt文件

[英]Creating a .txt file from a dictionary

I have a .txt file like this: 我有一个.txt文件,如下所示:

ID - NAME - LASTNAME - USER - PASSWORD

0001 - Oliver - Jackson - olson - pass123

0002 - Samuel - Depp - samuel - pass321

Then, I created a dictionary from the .txt file: 然后,我从.txt文件创建了一个字典:

{'0001': ['Oliver', 'Jackson', 'olson', 'pass123'], '0002': ['Samuel', 'Depp', 'samuel', 'pass321']}

Now, if someone wants to change one of the values inside the dictionary it's easy, but I need to overwrite the .txt file with such new values, something like this (no luck until now): 现在,如果有人想更改字典中的值之一,这很容易,但是我需要用这样的新值覆盖.txt文件,就像这样(到目前为止没有运气):

{'0001': ['Oliver', 'Jackson', 'newlog01', 'newpass01'], '0002': ['Samuel', 'Depp', 'samuel', 'pass321']}

0001 - Oliver - Jackson - newlog01 - newpass01

.

.

.

Thanks 谢谢

This solution will work for your current system, but it's recommended you don't store this data in your own custom format. 该解决方案适用于您当前的系统,但是建议您不要以自己的自定义格式存储此数据。 You should simply use the build in json library. 您应该只使用json库中的构建。

import json

input = '{\"0001\": [\"Oliver\", \"Jackson\", \"newlog01\", \"newpass01\"], \"0002\": [\"Samuel\", \"Depp\", \"samuel\", \"pass321\"]}'

data = dict()

try:
    data = json.loads(input)
except ValueError as e:
    print e

print 'ID - NAME - LASTNAME - USER - PASSWORD'
for key in sorted(data.keys()):
    print ' - '.join([key] + data[key])

Output: 输出:

ID - NAME - LASTNAME - USER - PASSWORD
0001 - Oliver - Jackson - newlog01 - newpass01
0002 - Samuel - Depp - samuel - pass321

You'll have to replace the entire file with the new contents 您必须用新内容替换整个文件

def read_file(filename):
    data = {}
    with open(filename, 'r') as fhd:
        for line in fhd:
            tokens = [token.strip() for token in line.split('-')]
            data[tokens[0]] = tokens[1:]
    return data


def write_file(filename, data):
    with open(filename, 'w') as fhd:
        for key in sorted(data.keys()):
            fhd.write('{} - {}\n'.format(key, ' - '.join(data[key])))

And use it as: 并将其用作:

if __name__ == '__main__':
    filename = 'test.dat'
    data = read_file(filename)
    data['0001'][1] = 'changed'
    write_file(filename, data)

There is no way around it. 没有其他办法了。 Data in disk is stored serially. 磁盘中的数据是串行存储的。

One quick way to do this is just create a serialization function that given one of your specially formatted dictionaries, will return it as a string encoded in your custom format. 一种快速的方法是创建一个序列化函数,该函数给出给定的一种特殊格式的字典,并将其作为以自定义格式编码的字符串返回。 Then just write that out to the original file and you're golden. 然后,只需将其写到原始文件中,您便会很高兴。

eg 例如

import os

def encode(data):
    header = "ID - NAME - LASTNAME - USER - PASSWORD"
    lines = [' - '.join([key] + values) for (key, values) in data.iteritems()]
    return (os.linesep+os.linesep).join([header] + lines)

Then you can write it back out again with something like: 然后,您可以使用类似以下内容再次写回:

with open('data.txt','w') as f:
    f.write(encode(d) + os.linesep)

Firstly you can use the json library , it's very good for your project. 首先,您可以使用json库,这对您的项目非常有用。 if you don't want to use json file and you need to change some datas from txt file : 如果您不想使用json文件,则需要从txt文件中更改一些数据:

import os 
new_txtfile=open("newfile.txt","w")
def get_the_datas_from_your_txtfile():
    #on this function you can do change as you want with dictionary
    # and now whrite the new dictionary to new_txtfile 
get_the_datas_from_your_txtfile()
your_txtfile.close()
new_txtfile.close() #her closing files 

os.remove("your_txtfile.txr")
os.renames("new_txtfile.txt","your_txtfile.txt")
#on thir we have removed the old file and changed the
#new files name to old files name 

This will do it about as tight as possible. 这将使它尽可能紧。

d_map = {'0001': ['Oliver', 'Jackson', 'olson', 'pass123'], '0002': ['Samuel', 'Depp', 'samuel', 'pass321']}
rv_str = ''
for key in d_map.keys():
    rv_str += key + ' - ' + ' - '.join(d_map[key]) + '\n'
with open('file.txt', 'w') as file_d:
    file_d.write(rv_str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM