My code is reading in a text file line by line. Each line is then trimmed of all whitespace to one space character and based on whether it matches the pattern it is then written to either the matched_data_file or the unmatched_data_file. I have to make use of lambda in this particular example. I think the error lies with the following line but I'm not 100% sure:
success(line=row) if pattern.match(line) else failure(line=row)
Any help is greatly appreciated, thanks in advance!
I get the following error message:
Traceback (most recent call last): File "model_dev_txt_to_csv.py", line 26, in process(source_filename) File "model_dev_txt_to_csv.py", line 23, in process process_line(line, lambda: write_csv(m, line), lambda: write_csv(u, line)) File "model_dev_txt_to_csv.py", line 12, in process_line return success(line=row) if pattern.match(line) else failure(line=row) TypeError: () got an unexpected keyword argument 'line'
The following is my current code:
import re
import csv
pattern = re.compile("([0-9]+) +([0-9\.-]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+)")
source_filename = "track_param_hist.txt"
matched_data_file = "good_hist_csv.csv"
unmatched_data_file = "bad_hist_csv.csv"
def process_line(line, success, failure):
# Make sure all whitespace is reduced to one space character
row = (' '.join(line.split())).split(' ')
success(line=row) if pattern.match(line) else failure(line=row)
def write_csv(file, line):
csv.writer(file).writerow(line)
def process(source):
print("Script for splitting text file into two separate csvs...")
with open(matched_data_file, 'w') as m:
with open(unmatched_data_file, 'w') as u:
with open(source) as f:
for line in f:
process_line(line, lambda: write_csv(m, line), lambda: write_csv(u, line))
if __name__ == "__main__":
process(source_filename)
lambda line: write_csv(...)line, call them with no arguments.process_lineturns alineinto arow, I think it'd be clearer if you used the namerowas a variable from that point. So the variable name in the lambda isrowand doesn't shadow the originallinesuccess(line=row) if pattern.match(line) else failure(line=row)doesn't make any sense. Maybe you meanif pattern.match(line): success(line=row) else: failure(line=row)