PermissionError caused by python reading and writing the same file multiple times: [Errno 13] Permission denied

PermissionError caused by python reading and writing the same file multiple times: [Errno 13] Permission denied

Problem Description

Today, in order to use python to extract information from word documents, I wrote a program to extract the contents of multiple words into excel, and wrote a function to save the data into excel. The code is as follows

    # 打开已有的Excel文件 并在末尾追加一行新数据
    # workBook = load_workbook(resultPath) #打开现有文件
    booksheet = workBook.active #当前工作表
    booksheet.append(list) # 在末尾追加一行新数据
    # workBook.save(resultPath)

If you add the statement in the comment, the file will be opened and closed every time you write, and a PermissionError will occur during multiple reads and writes.

Solution

When the file is opened at the beginning, the read and write functions no longer open and close, but only append the data, and then save and close the file after all reading and writing are completed.

Code modification: The commented code in the code in the description is deleted. The file is opened at the beginning of the main function and the file is closed at the end, that is, the file is opened and closed only once.

Guess you like

Origin blog.csdn.net/Zilong0128/article/details/120258450