test.csv
001_0004_1.bmp
002_0004_1.bmp
003_0004_1.bmp
004_0003_1.bmp
005_0003_1.bmp
006_0003_1.bmp
007_0002_1.bmp
008_0002_1.bmp
009_0002_1.bmp
010_0001_1.bmp
011_0001_1.bmp
012_0001_1.bmp
Suppose you have a file name like the contents of test.csv above. The BMP file described in this CSV has the following naming convention (it is a properly created naming convention),
FFF_TTTT_C.bmp
--F: Frame number --T: Some kind of index --C: Index of the thing in the picture --The above numbers and indexes are separated by'_'
The contents of the above CSV file are sorted by frame number, For some reason
** "I want to sort by some index of T!" **
I'm assuming sorting when such a case comes out.
I created a program with the idea. If you search carefully, the function Ippatsu Dawn! I feel like I can do it with ...
##
# coding:utf-8
##
import csv
import pprint as pp
##
#Sort by naming convention
# inputlist:List to sort
# key_number:Specify which character string to sort by
# key_Returns an empty list if number exceeds the number of naming convention divisions
##
def Sort_by_Key(input_list,key_number,split='_'):
#Split the file name and convert it to tuple format
file_sort = []
for t in input_list:
sp_t = t.split(split)
tap_sp_t = tuple(sp_t)
file_sort.append(tap_sp_t)
if len(file_sort[0]) < key_number:
return []
#sort
file_sort.sort(key=lambda t: t[key_number])
#Stick the splits together
output_file = []
for f in file_sort:
s = split.join(f)
output_file.append(s)
return output_file
def main():
#File reading
op = open('test.csv','r')
tpp = csv.reader(op)
#Extract only the first row of csv
test_file = []
for t in tpp:
test_file.append(t[0])
op.close()
#Original order
print("before")
pp.pprint(test_file)
file_save = Sort_by_Key(test_file,1)
print("\nafter")
pp.pprint(file_save)
#Conversion for storage
row = len(file_save)
col = 1
SaveList = [file_save[col * i: col * (i + 1)] for i in range(row)]
wp = open('output.csv','w')
writer = csv.writer(wp, lineterminator='\n')
writer.writerows(SaveList)
wp.close()
if __name__=="__main__":
main()
output.csv
010_0001_1.bmp
011_0001_1.bmp
012_0001_1.bmp
007_0002_1.bmp
008_0002_1.bmp
009_0002_1.bmp
004_0003_1.bmp
005_0003_1.bmp
006_0003_1.bmp
001_0004_1.bmp
002_0004_1.bmp
003_0004_1.bmp
[1] Reading and writing CSV with Python [2] Introduction to Python-Lists, Tuples, Dictionaries [3] Python: Sorting objects [4] Concatenate / split character strings in Python: join (), split () [5] convert a flat list to list of list in python [6] Library: pprint
Recommended Posts