Reputation: 1
I'm trying to get Python to write 5 lines of text to a CSV file, but to rewrite individual values into cells next to and not under.
At the moment the program is able to write all the variables, values as it wants but not properly arranged. However, csv.write and csv.writerows keeps overwriting from cell so that it adds values to cell [A1] then [A2] and not to [A1] then [B1]. Is there a function that I can use that writes everything on line like for example print(f"{variable}", end=', ')
I am very new to python sorry.
filename= 'test1.csv'
with open (filename, mode="w") as file: writer = csv.writer(file)
with open('1.json', 'r', encoding='utf-8') as f:
data = json.load(f)
categories = data['categories']
writer.writerow(f"URL,{','.join(categories)}")
for file in json_files:
with open(file, 'r', encoding='utf-8') as f:
data = json.load(f)
writer.writerow(url)
for category in data['categories']:
scores = data['categories'][category]['score']
writer.writerow(f"{scores}")
**# Desired output:
#
# ,
#
# URL,performance,accessibility,best-practices,seo,pwa,visibility,security,ads,mobile
# URL, 0.23, 0.56, 0.57, 0.67, 0.31, 0.67, 0.37, 0.54, 0.71,
# URL, 0.53, 0.53, 0.57, 0.8, 0.23, 0.67, 0.5, 0.62, 0.71,
# URL, 1, 1, 0.86, 0.88, 0.58, 0.67, 0.42, 0.38, 1,
#
#
#
# What ive got
#
# U,R,L,",",p,e,r,f,o,r,m,a,n,c,e,",",a,c,c,e,s,s,i,b,i,l,i,t,y,",",b,e,s,t,-,p,r,a,c,t,i,c,e,s,",",s,e,o,",",p,w,a,",",v,i,s,i,b,i,l,i,t,y,",",s,e,c,u,r,i,t,y,",",a,d,s,",",m,o,b,i,l,e
#
# URL
#
# 0,.,2,3
#
# 0,.,5,6
#
# 0,.,5,7
#
# 0,.,6,7
#
# 0,.,3,1
#
# 0,.,6,7
#
# 0,.,3,7
#
# 0,.,5,4
#
# 0,.,7,1
#
# URL
#
# 0,.,5,3
#
# 0,.,5,3
#
# 0,.,5,7
#
# 0,.,8
#
# 0,.,2,3
#
# 0,.,6,7
#
# 0,.,5
#
# 0,.,6,2
#
# 0,.,7,1
#
# URL
#
# 1
#
# 1
#
# 0,.,8,6
#
# 0,.,8,8
#
# 0,.,5,8
#
# 0,.,6,7
#
# 0,.,4,2
#
# 0,.,3,8
#
# 1
**
Upvotes: -1
Views: 98
Reputation: 1185
I assumed that your json
files were structured as follow (with only one JSON object per json
file):
{
"URL": <url_content>,
"performance": <performance_score>,
"accessibility": <accessibility_score>,
...
}
I came up with this code:
import json
files = ["1.json", "2.json"]
output = "output.csv"
if __name__ == "__main__":
aggregate = []
for file in files:
with open(file, "r", encoding="utf-8") as fp:
curr_data = json.load(fp)
if len(aggregate) == 0:
aggregate.append(",".join([f"{key}" for key in curr_data]))
aggregate.append(",".join([f"{curr_data[key]}" for key in curr_data]))
with open(output, "w", encoding="utf-8") as file:
file.write("\n".join(aggregate))
I created two dummy json
files:
1.json
{
"URL": "url1_content",
"performance": 0.23,
"accessibility": 0.56
}
2.json
{
"URL": "url2_content",
"performance": 0.53,
"accessibility": 0.53
}
This then creates the following output.csv
:
URL,performance,accessibility
url1_content,0.23,0.56
url2_content,0.53,0.58
Upvotes: -1