read_csv.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #! /usr/bin/env python
  2. # Sample of reading a CSV file
  3. #
  4. # https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python
  5. #
  6. import csv
  7. # # Define data
  8. # data = [
  9. # (1, "A towel,", 1.0),
  10. # (42, " it says, ", 2.0),
  11. # (1337, "is about the most ", -1),
  12. # (0, "massively useful thing ", 123),
  13. # (-2, "an interstellar hitchhiker can have.", 3),
  14. # ]
  15. # # Write CSV file
  16. # with open("test.csv", "wt") as fp:
  17. # writer = csv.writer(fp, delimiter=",")
  18. # # writer.writerow(["your", "header", "foo"]) # write header
  19. # writer.writerows(data)
  20. # Read CSV file
  21. for file in files:
  22. with open(file) as fp:
  23. reader = csv.reader(fp, delimiter=",", quotechar='"')
  24. # next(reader, None) # skip the headers
  25. # data_read = [row for row in reader]
  26. # print(data_read)
  27. lineno = 0
  28. num_column_headrs = 0
  29. print_first_n = 5
  30. for row in reader:
  31. lineno += 1
  32. if lineno == 1:
  33. num_column_headers = len(row)
  34. len_row = len(row)
  35. if len_row != num_column_headers:
  36. sys.stderr.write(f"Bad coumn count: line {lineno} has {len_row} colums. Expecting {num_column_headers}\n")
  37. print(row)
  38. sys.exit()
  39. if lineno <= print_first_n:
  40. print(row)
  41. if lineno > MAXLINES:
  42. break
  43. sys.stderr.write(f"Done: read {lineno} lines.\n")