Nathan1995
Nathan1995

Reputation: 111

file.write(line) not writing all of the lines in the file

I have the code below to check whether .txt files in a directory contain words from a chosen word list, it also prints to the console and writes the results to the out.txt file. However when there is more than one .txt file in the directory it only writes the last one checked to the out.txt file instead of all of them.

    self.wordopp = askdirectory(title="Select chat log directory")
    path = self.wordopp
    files = os.listdir(path)
    paths = []
    wordlist = self.wordop
    word = open(wordlist)
    l = set(w.strip().lower() for w in word)
    inchat = []
    for file in files:
        paths.append(os.path.join(path, file))
        with open(paths[-1]) as f:
            found = False
            file = open("out.txt", "w")
            for line in f:
                line = line.lower()
                if any(w in line for w in l):
                    found = True
                    print (line)
                    file.write(line)
                    if not found:
                        print("not here")

Upvotes: 0

Views: 983

Answers (1)

Václav Struhár
Václav Struhár

Reputation: 1769

The problem is in line: file = open("out.txt", "w") where you open out.txt for writing. The content of the file is erased.

Use file = open("out.txt", "a") instead and the file will be opened for appending the previously written content.

As stated in python documentation:

  • 'w' for only writing (an existing file with the same name will be erased)
  • 'a' opens the file for appending; any data written to the file is automatically added to the end

P.s. Don't forget to call file.close()

Upvotes: 1

Related Questions