首页 > 解决方案 > 将行写入文档时遇到问题

问题描述

我需要这个脚本来显示每个单词出现在哪一行。问题是我无法在文档中写入行

def WordOnLine():
    file = open("tekstbestand.txt","r")
    file2 = open("aantalwoorden","a")
    lineN = 0
    for line in file:
        sent = line.split()
        lineN += 1
        for word in sent:
            if len(word) >= 4:
                if word in file2:
                    word = word.replace(word,word+" " +lineN + "\n")
                else:
                    file2.append(word + " " + str(lineN) + "\n")
    file.close()
    file2.close()
WordOnLine()

标签: python

解决方案


尝试:

file2 = open("aantalwoorden","a+")

file2.write(word + " " + str(lineN) + "\n")

这是一些解释: https ://www.guru99.com/reading-and-writing-files-in-python.html


推荐阅读