My QA Projects

QA Projects I was involded.

View on GitHub

CSV (,)

’'’csv model, releasedate,memory, CPU PC, 08-1981, 8080 (…/) ‘’’

CSV Structure

Reading CSV files

  1. import csv module
  2. open a file object for reading
  3. open CSV reader object (accepts a file object as an argument)
  4. iterate CSV reader object (a row at a time)
  5. close the file object (not needed when using context manager)
import csv
csv.reader(csvfile)
import csv
with open ('ibmpcs.csv') as f:
    # if the mode is not specified, default is read
    rows = list(csv.reader(f))
    # creating a reader object by passing it the file object f
    # convert the iterator to list
    # set the variable rows to it
    header = rows[0]
    # first item in rows is the header
    print(f'{header[1]}\t{header[0]}')

    for row in rows[1:]:
        print(f'{row[1]}\t\t{row[0]}')
        # iteratign through the remaining rows
        # we will set the variable row to each row from the file
        # we skip the first row sinc ethat is our header: using a slice starting at index 1till the end of the list

Writing to CSV files

  1. import csv module
  2. open file object for writing
  3. open a CSV writer object
  4. Pass the file object to it
  5. Call write methods in the CSV writer object (this will write our data to the file)
  6. Close file object (skip that when using the context manager)
import csv
csv.writer(csvfile)
import csv
csvwriter.writerow(row)
import csv
header = ['ID', 'Name', 'Rank']
# setting up the header
data = [
    [1, 'Picard', 'Captain'],
    [2, 'Crisher', 'Commander'],
    [3, 'La Forge', 'Lt. Cmdr.'],
]
# a list of lists

with open ('starfleet.csv', 'w') as f:
    cw = csv.writer(f)
    # create a CSV file writer object
    # we pass it the file object f
    cw.writerow(header)
    # writes one row, the header, to the CSV file
    cw.writerows(data)
    # we don't need to convert the ID integer

  Strings   Variables   Lists   Tuples   Dictionary  
  Control   Function   Files   Exceptions      
  OOP   Algorithm   Data Structure   back