简体   繁体   中英

Create new file for each instance Python

I have a file with id numbers along with the specifics on event that is logged. (time, temp, location)

I want python to group all of the same id's into their own unique files, storing all of the even specifics from each record.

That is to say go through each record, if the id does not have a log file create one, if it does log the new record into that id's file.

Example input

1, 11:00, 70, port A
1, 11:02, 70, port B
2, 11:00, 40, blink
3, 11:00, 30, front

Desired output

file name "1" with :[11:00, 70, port A ; 11:02, 70, port B ]

file name "2" with :[11:00, 40, blink]

file name "3" with :[11:00, 30, front]

I am very new to python and I am having trouble finding a reference guide. If anyone knows a good place where I can look for an answer I would appreciate it.

This is pretty straightforward - presuming your file is as you described it however I am in Python 2.7 so I am not sure what the differences could be.

all_lines = open('c:\\path_to_my_file.txt').readlines()
from collections import defaultdict
my_classified_lines = defaultdict(list)
for line in all_lines:
    data_type, value1,value2,value3 = line.split(',')
    my_classified_lines[data_type).append(','.join([value1,value2,value3])


for data_type in my_classified_lines:
    outref = open('c:\\directory\\' + data_type + '.txt', 'w')
    outref.writelines(my_classified_lines[data_type])
    outref.close()

to understand this you need to learn about dictionaries - useful containers for data, file operations and loops

I found Dive into Python a great resource when I was starting up

I may not have exactly what you want after looking at your output mine would be like

11:00, 70, port A 11:02, 70, port B

I think you are stating that you want a list like object with semi-colons as the separator which to me suggests you are asking for a string with brackets around it. If your output is really as you describe it then try this

for data_type in my_classified_lines:
    outref = open('c:\\directory\\' + data_type + '.txt', 'w')
    out_list =[ ';'.join([item for item in my_classified_lines[data_type'])]
    outref.writelines(outlist) # should be only one line
    outref.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM