【问题标题】:how to fix the problem of writing on a file? [duplicate]如何解决在文件上写入的问题? [复制]
【发布时间】:2021-04-21 08:14:05
【问题描述】:

我有一个奇怪的问题。输出以下代码是一个文件,上面写有'software developer' 'software engennering' 'programming'。我希望拥有 list_of_lists 的全部元素。你能看出问题出在哪里吗?

list_of_lists=[['software developer', 'software engennering','programming'], ['data scientist', 'data analysis', 'AI developer']]

for x in range(0,len(list_of_lists)):               #for each cluster, do : 
    
    print( "=============== x = ",x," ================")              #will denote cluster number
    docs = list_of_lists[x]                                         
    fw = open("/Volumes/hard/Skyhive/one/list.txt",'w')
    fw.write((','.join(docs)).replace(","," "))                     #writing everything of one cluster in a file.
    countDocuments = len(docs)

【问题讨论】:

  • open("filename", "w") 将创建一个新文件,覆盖已经存在的文件。因为您是在 for 循环中创建文件,所以每次循环迭代都会覆盖文件。
  • 不推荐在 for 循环中打开文件。建议关闭。
  • 顺便说一句,Python 的 for 循环是 builtiterate over the items themselves 而不使用 index 。 enumerate 是一个 Python 函数,可让您在迭代时访问索引 - for x,docs in enumerate(list_of_lists):... 将是编写循环的规范方式。

标签: python file for-loop write


【解决方案1】:

你有 2 个问题 -

  1. 您一遍又一遍地打开文件而没有关闭它。

  2. 您第二次使用w 打开它,而不是a

如果您希望每次都重新打开文件,那么您应该在循环结束时关闭它。同样第一次你应该用w打开,第二次用a代表追加,并将追加到文件中,而不是重写它。

假设您希望编写整个内容,一个更简单的解决方案是从循环外部打开文件:

list_of_lists=[['software developer', 'software engennering','programming'], ['data scientist', 'data analysis', 'AI developer']]

fw = open("/Volumes/hard/Skyhive/one/list.txt",'w')

for x in range(0,len(list_of_lists)):               #for each cluster, do : 
    
    print( "=============== x = ",x," ================")              #will denote cluster number
    docs = list_of_lists[x]                                         
    
    fw.write((','.join(docs)).replace(","," "))                     #writing everything of one cluster in a file.
    countDocuments = len(docs)

fw.close()

【讨论】:

    【解决方案2】:

    您以'w'(写入)模式打开文件,这意味着每次迭代文件的先前内容都会被覆盖,请尝试仅打开一次。您也可以将fw.write((','.join(docs)).replace(","," ")) 更改为fw.write(' '.join(docs))

    list_of_lists=[['software developer', 'software engennering','programming'], ['data scientist', 'data analysis', 'AI developer']]
    
    fw = open("/Volumes/hard/Skyhive/one/list.txt",'w')
    for x in range(0,len(list_of_lists)):               #for each cluster, do : 
        
        print( "=============== x = ",x," ================")              #will denote cluster number
        docs = list_of_lists[x]
        fw.write(' '.join(docs))                     #writing everything of one cluster in a file.
        countDocuments = len(docs)
    fw.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2022-01-06
      • 1970-01-01
      • 2019-11-07
      • 2019-10-19
      相关资源
      最近更新 更多