Opening a text file does not need a third-party library. open is built in. Python treats files as text or binary. This page is about text files, which is the usual way to dump rows you have just read from a workbook.
"r" — read. The file must already exist."w" — write. If the file exists, its contents are erased. If it does not exist, Python creates it."a" — append. New text is added at the end of an existing file. The old text stays.Use "w" only when you mean to replace the file. Use "a" when you are adding another line to a log or a report.
fileobject = open("myfile.txt", "w", encoding="utf-8")
fileobject.write("Explaining Python open for writing in this tutorial\n")
fileobject.close()
write does not add a newline unless you include \n. After close, myfile.txt is in the current working directory.
The safer pattern is with. It closes the file even if a later line raises an error:
with open("myfile.txt", "w", encoding="utf-8") as fileobject:
fileobject.write("First line\n")
fileobject.write("Second line\n")
For Excel files, do not use open in write mode. An .xlsx file is a zip archive, and writing text over it destroys the workbook. Use openpyxl to create and save workbooks, and use open when the output really is a .txt or .csv file.
Libraries covered: openpyxl, xlrd, xlsxwriter, xlwt, and xlutils.