# Automate the Boring Stuff Chapter 13 - Spreadsheet to Text Files

The project outline:

Write a program that performs the tasks of the previous program in reverse order: the program should open a spreadsheet and write the cells of column A into one text file, the cells of column B into another text file, and so on.

My solution:

# A program to read a spreadsheet and write it to a text file with one text file per column

import sys, openpyxl
from pathlib import Path
from openpyxl.utils import get_column_letter

sheet = workbook.active
for column_index in range(1, sheet.max_column + 1):
file_path = save_folder / f"Text for column {get_column_letter(column_index)}.txt"
with open(file_path, "w", encoding="utf-8") as text_file:
for row_index in range(1, sheet.max_row + 1):
cell = sheet.cell(row=row_index, column=column_index)
if not cell.value:
text_file.write("\n")
else:
text_file.write(str(cell.value) + "\n")

if __name__ == "__main__":
save_folder = Path(sys.argv[2]) # The path of the folder to save the .txt files in


I decided to copy the formulas themselves rather than the result because the outline doesn't specify and the chapter doesn't discuss it.

• The description as quoted seems incomplete without knowing what the "previous program" is. But it seems that can be omitted, and you can simply give the requirements for this one. (It's hard to see how the order could be reversed - we can't write the data before we read it, can we?) Nov 10 at 12:57
• The tasks of the previous program were defined as follows: 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.
– ack
Nov 10 at 18:54

Use PEP8 to format your code. Two blank lines between functions, and two between imports and the first function (main).

In the main function, save_folder seems to be a Path object, but that's not obvious from reading the code until you use the / notation. Maybe use the type hints in the function definition.

def main(spreadsheet_path: Path, save_folder: Path):

It's possible your main function could be simplified using pandas, unless you were not allowed.