Guest User

Untitled

a guest
Aug 1st, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. How do I search a particular string out of file1, and update a csv file
  2. File1 is formatted as such:
  3. thisismy@email.com:20110708
  4. thisisnotmy@email.com:20110908
  5. thisisyour@email.com:20090807
  6. ...
  7.  
  8. import re
  9. emails = re.findall(r'^(.*@.*?):', open('filename.csv').read())
  10.  
  11. import csv
  12.  
  13. # 'b' flag for binary is necessary if on Windows otherwise crlf hilarity ensues
  14. with open('/path/to/file1.txt','rb') as fin:
  15. csv_reader = csv.reader(fin, delimiter=":")
  16. # Header in line 1? Skip over. Otherwise no need for next line.
  17. csv_reader.next()
  18. # populate dict with email address as key and date as value
  19. # dictionary comprehensions supported in 2.7+
  20. # on a lower version? use: d = dict((line[0],line[1]) for line in csv_reader)
  21. email_address_dict = {line[0]: line[1] for line in csv_reader}
  22.  
  23. # there are ways to modify a file in-place
  24. # but it's easier to write to a new file
  25. with open('/path/to/file2.txt','rb') as fin,
  26. open('/path/to/file3.txt','wb') as fou:
  27. csv_reader = csv.reader(fin, delimiter=":")
  28. csv_writer = csv.writer(fou, delimiter=":")
  29. # Header in line 1? Skip over. Otherwise no need for next line.
  30. csv_writer.writerow( csv_reader.next() )
  31. for line in csv_reader:
  32. # construct new line
  33. # looking up date value in just-created dict
  34. # the new date value is inserted position 5 (zero-based)
  35. newline = line[0:5]
  36. newline.append(email_address_dict[line[0]])
  37. newline.extend(line[6:])
  38. csv_writer.writerow(newline)
Add Comment
Please, Sign In to add comment