How do you read .txt files and export a csv file in Python

Question:

I have 4x .txt files. I want to set a list with certain words e.g. analyse, stack, ceiling, sky and I want to read from those .txt files and export a csv file with a table showing if the words in my list appear in those .txt files or not (boolean type), in Python.

I am working on Python with a course but I haven’t reached this section yet so any help is great, thanks!

I haven’t tried anything yet because I don’t have the knowledge of the functions needed to achieve this task.

Asked By: dev77cmd

||

Answers:

This should help with that. You want to make a list with items. Then create a function that will open, read, compare the files against your list and save the results. Then export to CSV.

In the future you should try to make less vague questions though.

import csv

search_words = ['analyse', 'stack', 'ceiling', 'sky']
def search_words_in_file(filename, search_words):
    with open(filename, 'r') as f:
        file_content = f.read()
    found_words = [word in file_content for word in search_words]
    return found_words
file_names = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt']
results = []
for file_name in file_names:
    found_words = search_words_in_file(file_name, search_words)
    results.append(found_words)


with open('results.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    header_row = ['Filename'] + search_words
    writer.writerow(header_row)
    for i, file_name in enumerate(file_names):
        row = [file_name] + [int(found) for found in results[i]]
        writer.writerow(row)
Answered By: Omnishroom
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.