How to create a dictionary based on a text file? - python

I'm writing a simple python game where I have a text file in the following format where the key on the left is the player's name and the value on the right is the player's score:
Name 134
Next Name 304958
Etc....
Question: How can I read in a text file in that format and create a dictionary from the values on each line, and once the player exits the program, the file is updated with the latest dictionary entries?
I already have some code commented out that I've started but have been unable to implement and get working. Any help is appreciated.
Here is my code:
# with open('scores.txt', 'r') as file:
# scores = {}
# for line in file:
# line = line.split()
# do stuff
# with open("scores.txt", "w") as f: # Save dictionary in file
# do stuff

To load that format:
with open('scores.txt', 'r') as infile:
scores = {}
for line in infile:
name, _, score = line.rpartition(' ')
scores[name] = int(score)
To save that format:
with open('scores.txt', 'w') as outfile:
for name, score in scores:
outfile.write('%s %s\n' % (name, score))
penne12 is correct, though. You could save a few lines of code by using the json library to store JSON instead of this particular text format.

Here's an example that uses JSON as suggested in the comments:
import json
def load_game_data():
data = None
with open('savegame.json', 'r') as savefile:
data = json.load(savefile)
return data
def save_game_data(data):
with open('savegame.json', 'w') as savefile:
json.dump(data, savefile)
# Store the game data as a dictionary:
data = { 'player_name' : 'wolfram', 'hp' : 8 }
save_game_data(data)
data = load_game_data()
print(data)
# prints {'player_name': 'wolfram', 'hp': 8}
print(data['player_name'])
print(data['hp'])
The data gets saved to disk as JSON and is loaded from disk as a dictionary, which is easy to use. You'll need to add code error handling, of course, this is just intended as a simple illustration.

Related

how can i add something to a dictionary in python which is present in another file from another python file

I am trying to get contacts in form of a python dictionary, this dictionary is present in the file named 'phone.py', and I want to add a contact to this dictionary from another function which is in another file named 'test.py'.
phone.py
phone_numbers={
'john': '+91123456789',
'berry': '+91987654321',
}
test.py
import phone.py
def add_contact():
name_contact = input("what is the name :")
phone_contact = input("contact number")
file = open("phone.py", "a", encoding='utf-8')
file.truncate()
file.write("'"+name_contact+"'" + ':'+"'+91"+phone_contact+"'"+",")
file.close()
add_contact()
what I am currently getting as result.
phone.py
phone_numbers={
'john': '+91123456789',
'berry': '+91987654321',
}'jerry': '+916543217890',
what I want it to be.
phone.py
phone_numbers={
'john': '+91123456789',
'berry': '+91987654321',
'jerry': '+916543217890',
}
Your file has textual content.
You can use the following method add lines to your file
def add_contact():
name_contact, phone_contact = read_param()
lines = None
with open('phone.py') as input_file:
lines = input_file.readlines()
lines[-1:] = "'{0}':'+91{1}',{2}".format(name_contact, phone_contact, '\r')
lines.append("}")
with open("phone.py", 'w') as output_file:
output_file.writelines(lines)
output_file.close()
def read_param():
name_contact = input("what is the name :")
phone_contact = input("contact number :")
return name_contact, phone_contact
But it is better to keep the data in json format or even simpler (not in the form of dict but one contact in each line)
for example
simple records like this
"john": "+91123456789"
"berry": "+91987654321"
.
.
.
and just append new line
def append_line():
with open('phone.py', 'a') as input_file:
name_contact, phone_contact = read_param()
input_file.writelines("'{0}':'+91{1}'".format(name_contact, phone_contact))
json
your file contents be like this
{
"john": "+91123456789",
"berry": "+91987654321"
}
and use the following code
def add_contact_json():
with open('phone.py') as json_file:
data = json.load(json_file)
name_contact, phone_contact = read_param()
data[name_contact] = "'+91{0}".format(phone_contact)
with open('phone.py', 'w') as json_file:
json.dump(data, json_file)

Have problem with input(using JSON) in file

How can I input information in json file with commas between values?
import json
class Calculation():
"""The Program class(ALL)"""
def __init__(self,money_earned = 0,money_spended = 0):
self.money_earned = money_earned
self.money_spended = money_spended
def m_s(self):
"""input daily spend to file"""
self.money_spended = str(input("How much money you spend today?"))
print(self.money_spended)
file = "data_txt_cat/spend.json"
with open(file,"a") as f_obj:
json.dump(self.money_spended,f_obj)
def m_e(self):
"""input daily earn to file"""
self.money_earned = input("How much money earned today? ")
print(self.money_earned)
file = "data_txt_cat/earn.json"
with open(file, "a") as f_obj:
json.dump(self.money_earned, f_obj)
spend = Calculation()
spend.m_s()
spend.m_e()
Currently this writes a file with "11""12" in it from that input, rather than JSON output
The problem is that you're writing a json object with just a single value, rather than really a json structure
Try putting your inputs into a dictionary or list and adding a newline
Additionally, if you're not making some sort of key-value mapping, consider if you're really using JSON at all
You may find it convenient to use a dictionary .update() method
import json
earned = {
"value": [] # this is the list being appended to
}
try:
with open("whatever.json", "r") as fh: # open for reading and writing
earned.update(json.load(fh))
except FileNotFoundError:
print("warning: no starting file")
with open("whatever.json", 'w') as fh: # NOTE clobbers - consider backup and swap
earned["value"].append(input("How much money earned today?: "))
json.dump(earned, fh) # rewrite file

how to read json file without using json libarary or without any other libarary in to dictionary or list?

I have a JSON file and i need to read it into dictionary or list without using and library.This is my file content.
{
"101":"Break and Enter Commercial",
"102":"Break and Enter Residential/Other",
"103":"Vehicle Collision or Pedestrian Struck (with Fatality)",
"104":"Vehicle Collision or Pedestrian Struck (with Injury)"
}
This is what i try
def read_codes(filename):
jsonData = {}
# empty list to append to it later
file = open(filename, "r")
for key in file:
print(key)
return jsonData
print(read_codes('codes.json'))
What about such way:
with open(file) as f:
your_dict = eval(f.read().replace('\n', ''))
You could open it as a text file. It would return you list, then filter the list as you require.
with open('file.json', 'r') as jsonFile:
json_obj = jsonFile.readlines()
json_obj = [(obj.rstrip()).lstrip()[:-1] for obj in json_obj[1:-1]]
print(json_obj)

Making a dictionary from a csv file with

Create a function that takes a file name (and path if needed) as the argument. In the function, open and read in the file mountains.csv. Use a try/catch to be sure the file exists and is readable. If the file location is wrong or it can't be opened, print an error that begins with "Error:". (You can test it with a junk path or filename that doesn't exist.)
Split each line by the comma, and make a dictionary where the key is the mountain name (the first element) and the height is the value, the second element. Make sure to convert the height to a number. Then print the keys and values of the dictionary using .items(), in readable sentences that say, for instance, "The height of K2 is 8611 meters." Return the dictionary at the end of the function.
Reminder about print with {} in your string: use print(string.format(variable)) to fill in the {} with your variable. If there are 2 {}'s, use .format(var1, var2)
This is what I got so far:
import csv
def mountain_height(filename):
""" Read in a csv file of mountain names and heights.
Parse the lines and print the names and heights.
Return the data as a dictionary.
The key is the mountain and the height is the value.
"""
mountains = dict()
msg = "The height of {} is {} meters."
err_msg = "Error: File doesn't exist or is unreadable."
# TYPE YOUR CODE HERE.
with open('mountains.csv', 'r') as handle:
reader = csv.reader(handle, delimiter=',')
for row in reader:
name = row[0]
height = row[1]
int(height)
dictionary = {name: height}
for k,v in dictionary.items():
print(k,v)
return dictionary
And there's the csv file:
You're nearly there. You simply need to add an entry to mountains for each iteration of the loop:
mountains = dict()
with open('mountains.csv', 'r') as handle:
reader = csv.reader(handle, delimiter=',')
for row in reader:
name = row[0]
height = row[1]
mountains[name] = int(height)
Don't forget to check if the file exists! I added an extra check so the function works with or without ".csv" file extension specified.
You also want to print a nice string using msg.format(name, height)
Lastly don't return the dictionary inside of the for loop! This ends your function and you will only see one message printed out.
For bonus points you can use csv.DictReader to read CSV files more efficiently. If the CSV does not have a header column, you need to pass fieldnames (i.e. name, height) yourself.
from csv import DictReader
def mountain_height(filename):
msg = "The height of {} is {} meters."
err_msg = "Error: File doesn't exist or is unreadable."
if filename.split('.')[-1] != 'csv':
filename += '.csv'
try:
open(filename)
except FileNotFoundError:
print(err_msg)
with open(filename) as f:
reader = DictReader(f, fieldnames=['name', 'height'], delimiter=',')
mountain_heights = {
row['name']: int(row['height']) for row in reader
}
for name, height in mountain_heights.items():
print(msg.format(name, height))
return mountain_heights

Save file without first and last double quotes

I am trying to save my data to a file. My problem is the file i saved contains double quotes at the first and the last of a line. I have tried many ways to solve it from str.replace(), strip, csv to json, pickle. However, the problem has been still persistent. I have got stuck with it. Please help me. I will detail my problem below.
Firstly, I have a file called angles.txt like that:
{'left_w0': -2.6978887076110842, 'left_w1': -1.3257428944152834, 'left_w2': -1.7533400385498048, 'left_e0': 0.03566505327758789, 'left_e1': 0.6948932961 181641, 'left_s0': -1.1665923878540039, 'left_s1': -0.6726505747192383}
{'left_w0': -2.6967382220214846, 'left_w1': -0.8440729275695802, 'left_w2': -1.7541070289428713, 'left_e0': 0.036048548474121096, 'left_e1': 0.166820410 49194338, 'left_s0': -0.7731263162109375, 'left_s1': -0.7056311616210938}
I read line by line from the text file and transfer to a dict variable called data. Here is the reading file code:
def read_data_from_file(file_name):
data = dict()
f = open(file_name, 'r')
for index_line in range(1, number_lines +1):
data[index_line] = eval(f.readline())
f.close()
return data
Then I changed something in the data. Something like data[index_line]['left_w0'] = data[index_line]['left_w0'] + 0.0006. After that I wrote my data into another text file. Here is the code:
def write_data_to_file(data, file_name)
f = open(file_name, 'wb')
data_convert = dict()
for index_line in range(1, number_lines):
data_convert[index_line] = repr(data[index_line])
data_convert[index_line] = data_convert[index_line].replace('"','') # I also used strip
json.dump(data_convert[index_line], f)
f.write('\n')
f.close()
The result I received in the new file is:
"{'left_w0': -2.6978887076110842, 'left_w1': -1.3257428944152834, 'left_w2': -1.7533400385498048, 'left_e0': 0.03566505327758789, 'left_e1': 0.6948932961 181641, 'left_s0': -1.1665923878540039, 'left_s1': -0.6726505747192383}"
"{'left_w0': -2.6967382220214846, 'left_w1': -0.8440729275695802, 'left_w2': -1.7541070289428713, 'left_e0': 0.036048548474121096, 'left_e1': 0.166820410 49194338, 'left_s0': -0.7731263162109375, 'left_s1': -0.7056311616210938}"
I cannot remove "".
You could simplify your code by removing unnecessary transformations:
import json
def write_data_to_file(data, filename):
with open(filename, 'w') as file:
json.dump(data, file)
def read_data_from_file(filename):
with open(filename) as file:
return json.load(file)

Categories