簡體   English   中英

從字典創建.txt文件

[英]Creating a .txt file from a dictionary

我有一個.txt文件,如下所示:

ID - NAME - LASTNAME - USER - PASSWORD

0001 - Oliver - Jackson - olson - pass123

0002 - Samuel - Depp - samuel - pass321

然后,我從.txt文件創建了一個字典:

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

現在,如果有人想更改字典中的值之一,這很容易,但是我需要用這樣的新值覆蓋.txt文件,就像這樣(到目前為止沒有運氣):

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

0001 - Oliver - Jackson - newlog01 - newpass01

.

.

.

謝謝

該解決方案適用於您當前的系統,但是建議您不要以自己的自定義格式存儲此數據。 您應該只使用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])

輸出:

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

您必須用新內容替換整個文件

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])))

並將其用作:

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

沒有其他辦法了。 磁盤中的數據是串行存儲的。

一種快速的方法是創建一個序列化函數,該函數給出給定的一種特殊格式的字典,並將其作為以自定義格式編碼的字符串返回。 然后,只需將其寫到原始文件中,您便會很高興。

例如

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)

然后,您可以使用類似以下內容再次寫回:

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

首先,您可以使用json庫,這對您的項目非常有用。 如果您不想使用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 

這將使它盡可能緊。

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