16 CSV & JSON Flashcards

1
Q
  1. How do you read a CSV file?
  2. How can you print out every row?
  3. How can you print the contents as a list?
  4. Access the second value of the second line?
A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you write to a CSV line?

A

> > > import csv
outputFile = open(‘output.csv’, ‘w’, newline=’’)
outputWriter = csv.writer(outputFile)
outputWriter.writerow([‘spam’, ‘eggs’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can you change the linespaces as well as the seperating value in a CSV?

A

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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is an alternative way to access CSV values in a certain column?

A

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’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can you use DictReader/ Writer methods when the file doesn´t have headings?

A

Yes - just implement the required headings in the DictReader:

> > > exampleDictReader = csv.DictReader(exampleFile, [‘heading1’])
for row in exampleDictReader:
… print(row[‘heading1’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are JSON and API´s useful for?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can you translate JSON data to Python values and vice versa?

A

imoprt json

JSON to Python:
»>json.loads(JsonData)

Python to JSON:
»>json.dumps(PythonData)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does a Json string look like?

A

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}’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly