Home > Mobile >  Remove an expression "dict_values([" from each line of a text file and remove closing &quo
Remove an expression "dict_values([" from each line of a text file and remove closing &quo

Time:05-16

I have a text file with thousands of lines each begining with the expression "dict_values(["followed by information that I want to keep in the line and ending in "])" that I also want to remove. An example input of line is as follows:

dict_values([['MC1006-4', '21374850', '36.12', '15.50', '', '', '', '', '', '', '', '17916'], 'Timecard-MC1006-4-20220509090149-Reported.csv', 'OlderVersion', 183])

How do I do this in python? Next I want to convert each comma separated value into its own column which would mean that ['MC1006-4', '21374850', '36.12', '15.50', '', '', '', '', '', '', '', '17916'] has its own column, then 'Timecard-MC1006-4-20220509090149-Reported.csv' has its own column and so on writing it all in a csv file. I would greatly appreciate the help! Thank you!

CodePudding user response:

sorry, but i can't understand what do you want to keep and what do you want to remove?

i understood that the structure of your dictionaries is this:

dict_values([[value1, value2, value3], value4, value5, value6]) (all of this in a string format)

so, looking at the little rappresentation i did before, what do you want to keep? value1, value2, value3 or value4, value5, value6

CodePudding user response:

import csv  
file_read = open('myinput.txt', 'r')
file_write = open('myoutput.csv', 'w')
writer = csv.writer(file_write)
for line in file_read:
   data = eval(line.replace("dict_values","list"))
   writer.writerow(data)
file_read.close()
file_write.close()

CodePudding user response:

I was able to solve my problem by reading the dictionary in with the following code

', '.join(str(x)for x in dir_B_dict[record_[i]].values())

so that now when it's writing to the text file, it truncates the dict_values and the brackets, and separates each value with a comma. Thank you for the help though!

  • Related