python - Writing files only once -
i have scenario this:
a = ["file1","file2","file3","file1","file2","file1","file5"] set_flag = 0 in range (len(a)): file_name = '%s.txt' %(a[i]) file_write = open('%s'%(file_name),'w') the above works , writes files. however,i want include logic such though file names appear more once in above list file_write should happen once. there should not multiple file writes. e.g. if file1 appears 4 times should written once. set_flag should set "1" if try writing file1 anywhere in code should should bypass file write.any ideas how accomplish , set such flag..?
use set(), stores single copy of item:
>>> a=["file1","file2","file3","file1","file2","file1","file5"] >>> set(a) set(['file3', 'file2', 'file1', 'file5']) for code, maintain order well.:
a=["file1","file2","file3","file1","file2","file1","file5"] seen=set() file in a: #you can iterate on list if file not in seen: #if file not in set write file_name= '%s.txt' %(file) file_write= open('%s'%(file_name),'w') seen.add(file) #add file seen
Comments
Post a Comment