16 CSV & JSON Flashcards
- How do you read a CSV file?
- How can you print out every row?
- How can you print the contents as a list?
- Access the second value of the second line?
1. >>> import csv >>> exampleFile = open('example.csv') >>> exampleReader = csv.reader(exampleFile) 2. >>> for row in exampleReader: print(row) 3. exampleList = list(exampleReader ) 4. exampleList[1][1]
How can you write to a CSV line?
> > > import csv
outputFile = open(‘output.csv’, ‘w’, newline=’’)
outputWriter = csv.writer(outputFile)
outputWriter.writerow([‘spam’, ‘eggs’])
How can you change the linespaces as well as the seperating value in a CSV?
With the lineterminator and the delimiter in the csvWriter variable:
> > > import csv
csvFile = open(‘example.tsv’, ‘w’, newline=’’)
csvWriter = csv.writer(csvFile, delimiter=’\t’, lineterminator=’\n\n’)
csvWriter.writerow([‘apples’, ‘oranges’, ‘grapes’])
csvFile.close()
What is an alternative way to access CSV values in a certain column?
Working with headers and the DictReader and DictWriter VSC Objects. They work like dicts:
> > > import csv
exampleFile = open(‘exampleWithHeader.csv’)
exampleDictReader = csv.DictReader(exampleFile)
for row in exampleDictReader:
… print(row[‘Header1’])
Can you use DictReader/ Writer methods when the file doesn´t have headings?
Yes - just implement the required headings in the DictReader:
> > > exampleDictReader = csv.DictReader(exampleFile, [‘heading1’])
for row in exampleDictReader:
… print(row[‘heading1’])
What are JSON and API´s useful for?
Many webites offer JSON content as a way for programs to interact with them. This is known as Application Programming Interface (API).
Accessing an API is the same as accessing any other web page via a URL. The difference is that the data returned by an API is formatted (with JSON, for example)
How can you translate JSON data to Python values and vice versa?
imoprt json
JSON to Python:
»>json.loads(JsonData)
Python to JSON:
»>json.dumps(PythonData)
What does a Json string look like?
It looks like a dictionary with ‘mars’ at start and end. Also, within the dict, the keys are always marked with “marks”:
jsonstring = ‘{“name”: “Zophie”, “isCat”: true}’