fork download
  1. #!/bin/bash
  2. # ideone boilerplate: run in temp dir
  3. t=$(mktemp -d -t ideone.XXXXXXXX) || exit
  4. trap 'rm -rf "$t"' ERR EXIT
  5. cd "$t"
  6.  
  7. cat <<\: >some.csv
  8. header,second,third
  9. "quoted
  10. value","over
  11. multiple
  12. lines","with
  13. ""quoted""
  14. value
  15. embedded"
  16. back,to,normal
  17. :
  18.  
  19. cat <<\: >prog.py
  20. import csv
  21.  
  22. def rawcsv(filename):
  23. with open(filename, "r") as csvdata, open(
  24. filename, "rb") as rawdata:
  25. reader = csv.reader(csvdata)
  26. prev = 0
  27. for row in reader:
  28. # Where is the file pointer now?
  29. pos = reader.line_num
  30. # Read the same amount of rawdata
  31. raw = b"".join([rawdata.readline() for _ in range(pos - prev)])
  32. prev = pos
  33. yield raw, row
  34.  
  35. for raw, row in rawcsv("some.csv"):
  36. print(f"Raw: {raw}")
  37. print(f"Row: {row}")
  38. :
  39.  
  40. python3 prog.py
  41.  
Success #stdin #stdout 0.03s 9676KB
stdin
Standard input is empty
stdout
Raw: b'header,second,third\n'
Row: ['header', 'second', 'third']
Raw: b'"quoted\nvalue","over\nmultiple\nlines","with\n""quoted""\nvalue\nembedded"\n'
Row: ['quoted\nvalue', 'over\nmultiple\nlines', 'with\n"quoted"\nvalue\nembedded']
Raw: b'back,to,normal\n'
Row: ['back', 'to', 'normal']