'Is it possible to save .xlsx as read-only using pandas?

It feels like there should be a way to save a .xlsx file as read-only using pandas' to_excel function or the XLSXwriter module.

I have looked at both documentations without luck.

to_excel: https://pandas.pydata.org/pandasdocs/stable/generated/pandas.DataFrame.to_excel.html

XLSXwriter: http://xlsxwriter.readthedocs.io/workbook.html

Is there another way to achieve this within pandas?



Solution 1:[1]

Not sure if it can be done with pandas but you can set it to read only after you create it.

import os
from stat import S_IREAD, S_IRGRP, S_IROTH
os.chmod(filename, S_IREAD|S_IRGRP|S_IROTH)

Solution 2:[2]

Still, if you want to use XLSXwriter

from xlsxwriter.workbook import Workbook
...
book = Workbook('file/path')
sheet = book.add_worksheet('worksheet_name')

# Add separate format for unlocked cells
unlocked = book.add_format({'locked': 0})
# Protect all cells in your sheet by default
sheet.protect()
...
# Write cell, locked by default
sheet.write(row_number, column_number, data)
# Write another cell, unlock it
sheet.write(row_number, column_number, data, unlocked)
...
book.close()

Solution 3:[3]

Similar answer to @Alex-Zisman, but for Windows:

import win32con, win32api, os

file_path = 'path/to/file.xlsx'
win32api.SetFileAttributes(file_path, win32con.FILE_ATTRIBUTE_READONLY)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A H
Solution 2 Yaroslav Varkhol
Solution 3 A H