只写一次文件

时间:2013-05-03 10:48:33

标签: python

我有这样的场景:

a = ["file1","file2","file3","file1","file2","file1","file5"]
set_flag = 0
for i in range (len(a)):
    file_name = '%s.txt' %(a[i])
    file_write = open('%s'%(file_name),'w')

以上工作和写入文件。 但是,我想要包含一个逻辑,即使某些文件名在上面的列表中出现多次,file_write也只会发生一次。不应该有多个文件写入。例如。如果file1出现4次,它应该只写一次。 有了这个,set_flag应设置为“1”,这样如果我尝试在我的代码中的任何地方写入file1,它应该绕过文件write.Any想法如何实现这一点并设置这样的标志..?

3 个答案:

答案 0 :(得分:4)

使用set(),它只存储项目的单个副本:

>>> a=["file1","file2","file3","file1","file2","file1","file5"]
>>> set(a)
set(['file3', 'file2', 'file1', 'file5'])

对于您的代码,这也将维护订单。:

a=["file1","file2","file3","file1","file2","file1","file5"]
seen=set()
for file in a:               #you can iterate over a list itself
    if file not in seen:     #if file is not in the set then write 
       file_name= '%s.txt' %(file)
       file_write= open('%s'%(file_name),'w')
       seen.add(file)  #add file to seen

答案 1 :(得分:1)

一个集合是一个好主意,所以你只需遍历列表中的唯一文件名。另外,不要使用range(len(...))和其他一些清理:

a = ["file1","file2","file3","file1","file2","file1","file5"]
set_flag = 0
for file_name in set(a):
    file_write = open(file_name + '.txt', 'w')

答案 2 :(得分:1)

如果出于某种原因需要创建输出文件的顺序,则可以使用OrderedDict(在2.7 +中):

for fname in OrderedDict.fromkeys(a):
    with open(fname, 'w') as fout:
        pass