I have a .txt file with the following contents:
norway sweden
bhargama bhargama
forbisganj forbesganj
canada usa
ankara turkey
I want to overwrite the file such that these are its new contents:
'norway' : 'sweden',
'bhargama': 'bhargama',
'forbisganj' : 'forbesganj',
'canada': 'usa',
'ankara': 'turkey'
Basically I want to turn the .txt file into a python dictionary so I can manipulate it. Are there built in libraries for this sort of task?
Here is my attempt:
import re
target = open('file.txt', 'w')
for line in target:
target.write(re.sub(r'([a-z]+)', r'':'"\1"','', line))
I'm succeeding in getting the quotes; but what's the proper regex to do what I described above?
d = dict(line.split() for line in open('file.txt'))