Case 1: Given a list of lists, how to serialize the data ...



1. What is a file format?A file format is a standard way in which information is encoded for storage in a file. First, the file format specifies whether the file is a binary or ASCII file. Second, it shows how the information is organized. For example, comma-separated values (CSV) file format stores tabular data in plain text.Working with CSV Files[ ]READING from CSVimport csvdatafile = open('data.csv', 'r')myreader = csv.reader(datafile)for row in myreader: print(row[0], row[1], row[2])Case 1: Split the string into lines of text, then pass into csv.reader()import csvrawdata = 'name,age\nDan,33\nBob,19\nSheri,42'myreader = csv.reader(rawdata.splitlines())for row in myreader: print(row[0], row[1])Case 2: Using the first line of a dataset as headers for each deserialized data object (dicts)import csvrawdata = 'name,age\nDan,33\nBob,19\nSheri,42'myreader = csv.DictReader(rawdata.splitlines())for row in myreader: print(row['name'], row['age'])Writing from CSVCase 1: Given a list of lists, how to serialize the data as a CSV text filedata = [ ['Dan', 42], ['Cordelia', 33], ['Sammy', 52] ]import csvwith open('outputdata.csv', 'w') as outfile: mywriter = csv.writer(outfile) # manually add header mywriter.writerow(['name', 'age']) for d in data: mywriter.writerow(d)Case 2: Given a list of dicts, serialize the data as CSVimport csvdata = [ {'name': 'Pat', 'age': 78}, {'name': 'Nancy', 'age': 23}, ]headers = ['name', 'age']with open('outputdata.csv', 'w') as outfile: mywriter = csv.DictWriter(outfile, fieldnames=headers) mywriter.writeheader() for d in data: mywriter.writerow(d)Special Casesyou could download the contents of the URL as text and save yourself the copy-pasting of that data:import requestsurl = ''rawtext = requests.get('url').textrecords = rawtext.splitlines()you could do the full steps, from downloading the data, to saving a local copy, to then reading text from a file object:import requestsurl = ''rawtext = requests.get('url').textdestname = 'simple-people.csv'with open(destname, 'w') as wf: wf.write(rawtext)with open(destname, 'r') as rf: rawtext = rf.read().splitlines() ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download