Reputation: 31
I have a .txt
file like this:
ID - NAME - LASTNAME - USER - PASSWORD
0001 - Oliver - Jackson - olson - pass123
0002 - Samuel - Depp - samuel - pass321
Then, I created a dictionary from the .txt file:
{'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):
{'0001': ['Oliver', 'Jackson', 'newlog01', 'newpass01'], '0002': ['Samuel', 'Depp', 'samuel', 'pass321']}
0001 - Oliver - Jackson - newlog01 - newpass01
.
.
.
Thanks
Upvotes: 0
Views: 107
Reputation: 3852
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)
Upvotes: 0
Reputation: 106
Firstly you can use the json
library , it's very good for your project.
if you don't want to use json
file and you need to change some datas from txt file :
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
Upvotes: 0
Reputation:
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.
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
Upvotes: 1
Reputation: 5518
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.
e.g.
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)
Upvotes: 0
Reputation: 1
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.
Upvotes: 0