I have some invoice items:
lista_items = {}
lineNumber = 0
for line in self.invoice_line_ids:
lineNumber = lineNumber + 1
print lineNumber
lista_items["numeroLinea"] = [lineNumber]
lista_items["cantidad"] = [line.quantity]
lista_items["costo_total"] = [line.price_subtotal]
lista_items["precioUnitario"] = [line.price_unit]
lista_items["descripcion"] = [line.name]
# for line_tax in line.invoice_line_tax_ids:
# print line_tax.amount
# print line_tax.id
# # print line.invoice_line_tax_ids
return lista_items
I need to save the items in a dictionary and after that to save it to a JSON.
How can I do it?
You can use json.dump() to save a dictionary to a file. For example:
# note that output.json must already exist at this point
with open('output.json', 'w+') as f:
# this would place the entire output on one line
# use json.dump(lista_items, f, indent=4) to "pretty-print" with four spaces per indent
json.dump(lista_items, f)
In the following code just replace the variable d with your dictionary and put your filename in place of 'json_out'. Take note of the parameter w+, it opens the file both for reading and writing and overwrites the existing file if any.
Also note that there is also 'dumps' method in json which will give you string representation of the dict.
import json
d = {'x':2,'y':1}
out_file = open('json_out','w+')
json.dump(d,out_file)
just dump the lista_items in a json file like:
import json
lista_items = {}
lineNumber = 0
for line in self.invoice_line_ids:
lineNumber = lineNumber + 1
lista_items["numeroLinea"] = [lineNumber]
lista_items["cantidad"] = [line.quantity]
lista_items["costo_total"] = [line.price_subtotal]
lista_items["precioUnitario"] = [line.price_unit]
lista_items["descripcion"] = [line.name]
with open('file.json', 'w') as fp:
json.dump(lista_items, fp, indent=4)
Related
My program takes a csv file as input and writes it as an output file in json format. On the final line, I use the print command to output the contents of the json format file to the screen. However, it does not print out the json file contents and I don't understand why.
Here is my code that I have so far:
import csv
import json
def jsonformat(infile,outfile):
contents = {}
csvfile = open(infile, 'r')
reader = csvfile.read()
for m in reader:
key = m['No']
contents[key] = m
jsonfile = open(outfile, 'w')
jsonfile.write(json.dumps(contents))
csvfile.close()
jsonfile.close()
return jsonfile
infile = 'orders.csv'
outfile = 'orders.json'
output = jsonformat(infile,outfile)
print(output)
Your function returns the jsonfile variable, which is a file.
Try adding this:
jsonfile.close()
with open(outfile, 'r') as file:
return file.read()
Your function returns a file handle to the file jsonfile that you then print. Instead, return the contents that you wrote to that file. Since you opened the file in w mode, any previous contents are removed before writing the new contents, so the contents of your file are going to be whatever you just wrote to it.
In your function, do:
def jsonformat(infile,outfile):
...
# Instead of this:
# jsonfile.write(json.dumps(contents))
# do this:
json_contents = json.dumps(contents, indent=4) # indent=4 to pretty-print
jsonfile.write(json_contents)
...
return json_contents
Aside from that, you aren't reading the CSV file the correct way. If your file has a header, you can use csv.DictReader to read each row as a dictionary. Then, you'll be able to use for m in reader: key = m['No']. Change reader = csvfile.read() to reader = csv.DictReader(csvfile)
As of now, reader is a string that contains all the contents of your file. for m in reader makes m each character in this string, and you cannot access the "No" key on a character.
a_file = open("sample.json", "r")
a_json = json.load(a_file)
pretty_json = json.dumps(a_json, indent=4)
a_file.close()
print(pretty_json)
Using this sample to print the contents of your json file. Have a good day.
I have a JSON file like this: [{"ID": "12345", "Name":"John"}, {"ID":"45321", "Name":"Max"}...] called myclass.json. I used json.load library to get "ID" and "Name" values.
I have another .txt file with the content below. File name is list.txt:
Student,12345,Age 14
Student,45321,Age 15
.
.
.
I'm trying to create a script in python that compares the two files line by line and replace the student ID for the students name in list.txt file, so the new file would be:
Student,John,Age 14
Student,Max,Age 15
.
.
Any ideas?
My code so far:
import json
with open('/myclass.json') as f:
data = json.load(f)
for key in data:
x = key['Name']
z = key['ID']
with open('/myclass.json', 'r') as file1:
with open('/list.txt', 'r+') as file2:
for line in file2:
x = z
try this:
import json
import csv
with open('myclass.json') as f:
data = json.load(f)
with open('list.txt', 'r') as f:
reader = csv.reader(f)
rows = list(reader)
def get_name(id_):
for item in data:
if item['ID'] == id_:
return item["Name"]
with open('list.txt', 'w') as f:
writer = csv.writer(f)
for row in rows:
name = get_name(id_ = row[1])
if name:
row[1] = name
writer.writerows(rows)
Keep in mind that this script technically does not replace the items in the list.txt file one by one, but instead reads the entire file in and then overwrites the list.txt file entirely and constructs it from scratch. I suggest making a back up of list.txt or naming the new txt file something different incase the program crashes from some unexpected input.
One option is individually open each file for each mode while appending a list for matched ID values among those two files as
import json
with open('myclass.json','r') as f_in:
data = json.load(f_in)
j=0
lis=[]
with open('list.txt', 'r') as f_in:
for line in f_in:
if data[j]['ID']==line.split(',')[1]:
s = line.replace(line.split(',')[1],data[j]['Name'])
lis.append(s)
j+=1
with open('list.txt', 'w') as f_out:
for i in lis:
f_out.write(i)
itemsInExistence = []
item = {}
item['name'] = input("What do you want the new item to be called? ")
item['stats'] = int(input("What is its stat? "))
item['rank'] = int(input("What is its base rank? "))
item['amount'] = int(input("How many of it are there? "))
for i in range(item['amount']):
itemsInExistence.append(item)
def save_list2():
with open('itemsleft.txt', 'wb') as f:
i = 0
for item in itemsInExistence:
pickle.dump(itemsInExistence, f)
i += 1
I tried to save it both normally and with pickle, but neither keeps the dictionary's values. I need to save the dictionary to the file and retrieve it from the file with 'stats', 'rank', 'amount' still being integers and still separate from the rest of the line. (Keep in mind that there will be more than one saved item in itemsInExistence, both to be saved and loaded.)
def save_list2():
ii = 0
for i in itemsInExistence:
d = itemsInExistence[ii]
json.dump(d, open(files2, 'w'))
ii += 1
def load_list2():
with open(files2,'r') as a:
for line in a:
line = line.strip()
itemsInExistence.append(line)
You may use JSON format to store a dict into a file, it's quite easy
import json
file = "foofile"
d = dict()
# fill d
# save data : format the dict to a string and it into the file
json.dump(d, open(file, 'w'))
# read data : read the file's content and parse to a dict
a = json.load(open(file))
def load_from_file():
d = {} # create empty dict
file = open("players.txt", "r")# open file for reading
line = file.readline()
file.close()# we’re done with the file
list = line.split(",")
prop = {"position":"","number":"","name":"","birth":"","id":""}
keys = (sorted(prop))
num = 0
for key in keys:
d[key] = list[num]
num += 1
return d
The problem is that whenever the loop returns to this function it reads the same line! and i want the offset to drop a new line
The problem is that you're telling the program to only read the first line of the file every time you call the function at the file.readline() statement. You should read all the file in at once into a list, then loop through the lines that have been read into the list.
Example:
def load_from_file():
with open("players.txt", "r") as myfile # open file for reading
myfile = file.readlines()
return myfile
def create_dictionary(line):
d = {}
list = line.split(",")
prop = {"position":"","number":"","name":"","birth":"","id":""}
keys = (sorted(prop))
num = 0
for key in keys:
d[key] = list[num]
num += 1
return d
data = []
filedata = load_from_file()
for line in filedata:
data.append(create_dictionary(line))
P.S. Not sure what all you're trying to do with data, but this should help you get the gist.
Using DictReader from the csv module:
def load_from_file():
with open("players.txt") as players:
fields = ["birth", "id", "name", "number", "position"]
reader = csv.DictReader(players, fields)
return list(reader)
Here i have a code written to extract "locus_tag" of gene using "id". How can i save the output from this into a file in a tab seperated format????code adopted and modified https://www.biostars.org/p/110284/
from Bio import SeqIO
foo = open("geneid.txt")
lines = foo.read().splitlines()
genbank_file = open("example.gbk")
for record in SeqIO.parse(genbank_file, "genbank"):
for f in record.features:
if f.type == "CDS" and "protein_id" in f.qualifiers:
protein_id = f.qualifiers["protein_id"][0]
if protein_id in lines:
print f.qualifiers["protein_id"][0],f.qualifiers["locus_tag"][0]
Try adding something like this -- but you will need to make certain the indentations are correct with the code that you have already written.
with open(your_outputFileName, 'w') as outputFile:
string = '\t'.join([f.qualifiers['protein_id'][0],f.qualifiers['locus_tag'][0]])
outputFile.write(string + '\n')
You should also consider opening your initial file using "with". This will automatically close the file when you are done with it -- otherwise -- be certain to close the file (e.g., foo.close()).
for record in SeqIO.parse(genbank_file, 'genbank'):
for f in record.features:
if f.type == 'CDS' and 'protein_id' in f.qualifiers:
protein_id = f.qualifiers['protein_id'][0]
if protein_id in lines:
print f.qualifiers['protein_id'][0],f.qualifiers['locus_tag'][0]
with open('your_outputFileName', 'w') as outputFile:
string = '\t'.join([f.qualifiers['protein_id'][0],f.qualifiers['locus_tag'][0]]) + '\n'
outputFile.write(string)