Python 从字典创建.txt文件

Python 从字典创建.txt文件,python,dictionary,Python,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',

我有一个
.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文件,类似这样的内容(到目前为止运气不好):


谢谢

此解决方案适用于您当前的系统,但建议您不要以自定义格式存储此数据。您只需使用内置的
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_文件(文件名):
数据={}
打开(文件名为“r”)作为fhd:
对于fhd中的线路:
tokens=[token.strip()表示第行中的令牌。拆分('-')]
数据[令牌[0]]=令牌[1:]
返回数据
def write_文件(文件名、数据):
打开(文件名为“w”)作为fhd:
对于已排序的键(data.keys()):
write('{}-{}\n'.格式(键''-'.join(数据[key]))
并将其用作:

如果uuuu name_uuuu=='\uuuuuuu main\uuuuuu':
文件名='test.dat'
数据=读取文件(文件名)
数据['0001'][1]=“已更改”
写入文件(文件名、数据)

这是没有办法的。磁盘中的数据是按顺序存储的。

一种快速方法是创建一个序列化函数,给定一个特殊格式的字典,它将以自定义格式编码的字符串形式返回。然后把它写在原始文件里,你就是黄金

e、 g

然后,您可以使用以下内容再次将其写出来:

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)

您可以更改文件中的字符串,然后再次运行程序,使用本机Python模块
json
创建字典。不需要浪费JSON之间的转换。您的数据结构是向后的。你不应该创建一个指向列表的
dict
,而应该创建一个包含
dict:
[{'NAME':'Oliver','LASTNAME':'Jackson','USER':'olson','PASSWORD':'pass123},{next USER},{etc}]的
列表。你不必替换整个文件。如果小心的话,您可以使用
seek()
write()
。您必须确保替换字符串的大小与被替换字符串的大小相同。我明白您的意思,您可以通过让每个字段都有一个保留的可用字节来破解解决方案。
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)