I want to nest JSON from flatten CSV file, how to create a parent category using all the subcategories in flatten CSV file. Please check out the format of data in given image below.
Image of the formats are in here
Any help would be appreciated!
You can read about csv module here:
https://docs.python.org/3/library/csv.html
There is a class there called DictReader which takes a CSV file and puts it in a dictionary, and from there the way to json is easy.
The following example is presented there:
import csv
with open('names.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['first_name'], row['last_name'])
Output:
Eric Idle John Cleese
Related
I have a problem with a csv :
CSV image problem
I have HTML code in a csv but in some rows, the code broke the csv format.
I would like to know if somebody know how to solve this problem with python.
I would to fix the csv to get this format.
csv with format
I try to use with open and pandas to create a new csv
import csv
with open('csv_problem.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
I have a directory containing multiple csv's that I would to read into a single dictionary. The dictionary would use the original file names as keys and the contents of the csv's as values. I don't want to use pandas because I am new to Python and want to understand these tasks first before pulling out the big guns. I would like to use DictReader for the task. Here is the code I have so far below. It works fine for one file at a time. Help is greatly appreciated.
def read_lines():
data = []
with open('vari_late_low_scores.csv', newline='') as stream:
reader = csv.reader(stream, delimiter=',', skipinitialspace=True)
for row in reader:
data.append(row)
return data
Thank you!
I'm writing a dictionary into a csv file using Python's csv library and a DictWriter object like so:
with open('test.csv', 'w', newline='') as fp:
fieldnames = [<fieldnames for csv DictWriter>]
dict_writer = csv.DictWriter(fp, fieldnames=fieldnames)
dict_writer.writeheader()
dict_writer.writerow(<some dictionary here>)
The result is that if i have a long name as one of the dictionary's values the cells look like this:
But i want it to look like this:
Is there a way to fit the cells' size to the string lengths ? I imagine this is a relatively common issue since you don't want to manually do it each time you open a csv file.
How can i fit it beforehand ?
A CSV does not have formatting information. It only have data. It is up to the viewer configuration how to resize the cells.
If you really need formatting, you should write in the file format of the receiving application (.ods, .xls, .xlsx...).
I have written simple code to make a list of strings, all I want is to export that list on its own to a csv file that I can open with excel. I have read through multiple answers and still can't get it to work. Running python 3. I believe my problem is with either creating the new csv file or having it find and write to a preexisting one, any ideas on this?
Check out the csv module. It would look something like this:
import csv
mylist = ['foo', 'bar', 'baz']
with open('myfile.csv', 'w', newline='\n') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(['Header1', 'Header2', 'Header3'])
csvwriter.writerow(mylist)
Output:
Header1,Header2,Header3
foo,bar,baz
This code will create a file if it doesn't exist, or overwrite an existing file called myfile.csv. More info here.
yourlist = ['string1', 'string2']
data = ','.join(yourlist)
fh = open('myfile.csv', 'w+')
fh.write(data)
fh.close()
If you multiple lists(say list of lists) to be written to CSV, then loop them over using for. Above example is to do using without any imports.
You can also do alternatively using csv module (import csv)
This is my code that adds the data to the CSV file known as studentScores.csv
myfile = open("studentScores.csv", "a+")
newRecord = Score, Name, Gender, FormGroup, Percentage
myfile.write(str(newRecord))
myfile.write("\n")
myfile.close()
As a part of my task, I need to alphabetise the data in the CSV, I have searched, and searched for a solution, but I am unable to find a working solution for me. I am pretty new to Python, so the simplest solution will be appreciated.
import csv
from operator import itemgetter
with open('studentScores.csv', 'r') as f:
data = [line for line in csv.reader(f)]
newRecord = [Score, Name, Gender, FormGroup, Percentage]
data.append(newRecord)
data.sort(key=itemgetter(1)) # 1 being the column number
with open('studentScores.csv', 'w') as f:
csv.writer(f).writerows(data)
First of all, this uses functions from the csv module for properly parsing and creating CSV syntax. Secondly, it reads all existing entries into data, appends the new record, sorts all records, then dumps them back to the file.
If you're using a header row in your CSV file to add names to columns, look at DictReader and DictWriter, that would allow you to handle columns by name, not number (e.g. in the sorting step).