The project outline:
Write a program to read in the contents of several text files (you can make the text files yourself) and insert those contents into a spreadsheet, with one line of text per row. The lines of the first text file will be in the cells of column A, the lines of the second text file will be in the cells of column B, and so on.
Use the readlines() File object method to return a list of strings, one string per line in the file. For the first file, output the first line to column 1, row 1. The second line should be written to column 1, row 2, and so on. The next file that is read with readlines() will be written to column 2, the next file to column 3, and so on.
My solution:
# A program to read text files and write it to an Excel file with one line per row
# Usage: python text_to_spreadsheet.py "folder to search for text files" "save location for spreadsheet"
import sys, openpyxl
from pathlib import Path
def main(search_folder, save_path):
workbook = openpyxl.Workbook()
sheet = workbook.active
for column_index, filename in enumerate(search_folder.glob("*.txt")):
with open(filename, "r", encoding="utf-8") as text_file:
for row_index, line in enumerate(text_file.readlines()):
sheet.cell(row=row_index + 1, column=column_index + 1).value = line.strip()
workbook.save(save_path)
if __name__ == "__main__":
search_folder = Path(sys.argv[1]) # the folder with text files to search
save_path = Path(sys.argv[2]) # the path of the new spreadsheet (must end in .xlsx)
main(search_folder, save_path)