Reputation: 11
I am new to programming. I currently have the dictionary as follows and I would like to write it to a text file(separated by lines) to replace the original content in my text file. I have changed a few values and added in new keys, and was wondering how to go about doing it.
Below is the dictionary I would like to replace the original text file with:
cars={'Honda\n':['10/11/2020\n','red\n','firm and sturdy\n'
'breaks down occasionally\n'],'Toyota\n':['20/12/2005\n','indigo\n'
'big and spacious\n', 'fuel saving\n'],'Maserati\n':['10/10/2009\n','silver\n','fast and furious\n','expensive to maintain\n'],'Hyundai\n':['20/10/2000\n','gold\n','solid and reliable\n','slow acceleration\n']
Original file:
Honda
10/11/2010
blue
strong and sturdy
breaks down occasionally
Toyota
20/15/2005
indigo
big and spacious
Maserati
10/10/2009
silver
fast and furious
expensive to maintain
accident prone
Desired file:
Honda
10/11/2020
red
firm and sturdy
breaks down occasionally
Toyota
20/12/2005
indigo
big and spacious
fuel-saving
Maserati
10/10/2009
silver
fast and furious
expensive to maintain
Hyundai
20/10/2000
gold
solid and reliable
slow acceleration
Here is what I have done:
with open('cars.txt', 'w') as f:
f.write(str(cars))
f.close()
But it only prints the dictionary instead of the desired file. Can I know how to go about it?
Upvotes: 0
Views: 110
Reputation: 1830
There are multiple problems here:
dict
to a file.
dict
to a str
, like this: dict_as_str = str(dict)
, then f.write(dict_as_str)
f.write
converts it the same way print
would, so if you run print(dict_as_str)
, it would basically look like a dict.
Upvotes: 0
Reputation:
Based on your debug error, you should only convert your dict into str like this
with open('cars.txt', 'w') as f:
f.write(str(cars))
f.close()
Upvotes: 0
Reputation: 9061
First split the original file data using the delimiter '\n\n'
. Then use the dictionary access the new data. then write the result to new file.
with open('cars.txt') as fp, open('new_cars.txt', 'w') as fw:
for car in fp.read().split('\n\n'):
car_name = car.split('\n', 1)[0] + '\n'
fw.write(car_name + ''.join(cars[car_name]) + '\n')
Upvotes: 0
Reputation: 678
In your write statement, you could simply do this:
f.write('\n'.join(car + ''.join(cars[car]) for car in cars))
Upvotes: 0
Reputation: 1392
You can't just dump the dictionary because as far as the write
method is concerned you are trying to dump the memory location.
You need to go through each dictionary key and item like so.
You also don't need to close the file because when you leave the with open
loop it will close on it's own.
with open('cars.txt', 'w') as f:
for car, vals in cars.items:
f.write(car)
for val in values:
f.write(val)
Note: I have not tested any of this.
Upvotes: 1