Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XLS Files Renamed in Python Getting Corrupted?

I'm new-ish to Python and I'd like to accomlish a simple task but I'm a little stuck/confused. I simply have a task I'd like to automate, which is appending the current date to the filename of an excel file for work.

import os
import sys
import datetime


src_dir = os.path.normpath('\\\\EXAMPLE_SERVER_NAME\\x$\\Clients\\Public\\')
dir = os.listdir(src_dir)
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
date = str(month) + '.' + str(day) + '.' + str(year)
new_filename = ''

for filename in dir:
    if filename.startswith('MJ_ProdMaster'):
        str_index = filename.index('.',0,len(filename))
        new_filename = filename[:(str_index)] + ' ' + str(date) + '.xls' 
        new_filename = os.path.join(src_dir, new_filename)
        old_filename = os.path.join(src_dir, filename)
        os.rename(old_filename,new_filename)

When I open up the freshly renamed XLS file in Libre Office the warning I receive is:

The file is corrupt and therefore cannot be opened. LibreOffice can try to repair the file.

The corruption could be the result of document manipulation or of structural document damage due to data transmission.

So my renaming of the file has clearly corrupted it, even though superficially it seemed to rename files correctly. I am not sure exactly HOW I have corrupted it though. A secondary (but equally important) question is what should I have done differently in my script, because I'm clearly not accomplishing the renaming task successfully.

Edit: If it is any additional info, when I try to repair the file within Libre Office the error Read-Error: Unknown or unsupported Excel file format.

like image 1000
Stephen Tetreault Avatar asked Sep 11 '26 20:09

Stephen Tetreault


1 Answers

Instead of

new_filename = filename[:(str_index)] + ' ' + str(date) + '.xls'

try

new_filename = filename[:(str_index)] + ' ' + str(date) + filename[(str_index):]

This will maintain any previous suffixes, and will be fault-tolerant for multiple . characters in the file name.

like image 165
MattDMo Avatar answered Sep 14 '26 10:09

MattDMo