zharry

CSV from Textfile

May 21st, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. import csv
  2. import re
  3.  
  4. fieldnames = ['NAME', 'DESCR', 'PID', 'VID', 'SN']
  5. with open('test.csv', 'w') as output:
  6. writer = csv.DictWriter(output, fieldnames=fieldnames)
  7. writer.writeheader()
  8.  
  9. with open('input.txt', 'r') as input:
  10. lines = input.readlines()
  11.  
  12. for i in range(1, len(lines), 3):
  13. line = lines[i].strip() + "," + lines[i + 1].strip()
  14. sections = re.split("([A-Z])\w+:", line)
  15.  
  16. curCol = {}
  17. for j in range(1, len(sections), 2):
  18. key = fieldnames[j / 2]
  19. value = sections[j + 1].strip().strip(",").strip("\"")
  20. curCol[key] = value
  21. writer.writerow(curCol)
Advertisement
Add Comment
Please, Sign In to add comment