Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- How do I search a particular string out of file1, and update a csv file
- File1 is formatted as such:
- thisismy@email.com:20110708
- thisisnotmy@email.com:20110908
- thisisyour@email.com:20090807
- ...
- import re
- emails = re.findall(r'^(.*@.*?):', open('filename.csv').read())
- import csv
- # 'b' flag for binary is necessary if on Windows otherwise crlf hilarity ensues
- with open('/path/to/file1.txt','rb') as fin:
- csv_reader = csv.reader(fin, delimiter=":")
- # Header in line 1? Skip over. Otherwise no need for next line.
- csv_reader.next()
- # populate dict with email address as key and date as value
- # dictionary comprehensions supported in 2.7+
- # on a lower version? use: d = dict((line[0],line[1]) for line in csv_reader)
- email_address_dict = {line[0]: line[1] for line in csv_reader}
- # there are ways to modify a file in-place
- # but it's easier to write to a new file
- with open('/path/to/file2.txt','rb') as fin,
- open('/path/to/file3.txt','wb') as fou:
- csv_reader = csv.reader(fin, delimiter=":")
- csv_writer = csv.writer(fou, delimiter=":")
- # Header in line 1? Skip over. Otherwise no need for next line.
- csv_writer.writerow( csv_reader.next() )
- for line in csv_reader:
- # construct new line
- # looking up date value in just-created dict
- # the new date value is inserted position 5 (zero-based)
- newline = line[0:5]
- newline.append(email_address_dict[line[0]])
- newline.extend(line[6:])
- csv_writer.writerow(newline)
Add Comment
Please, Sign In to add comment