在Python中重命名的XLS文件被破坏了吗?

2024-04-19 21:25:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我想完成一个简单的任务,但我有点困惑。我只是想自动化一个任务,就是将当前日期附加到excel文件的文件名中。在

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)

当我在Libre Office中打开新重命名的XLS文件时,我收到的警告是:

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.

因此,我对文件的重命名显然已经损坏了它,尽管表面上它似乎正确地重命名了文件。我不知道我到底是怎么把它弄坏的。第二个(但同样重要的)问题是,我应该在脚本中做些什么不同的事情,因为我显然没有成功地完成重命名任务。在

编辑:如果是其他信息,当我试图在Libre Office中修复文件时,错误读取错误:未知或不支持的Excel文件格式。


Tags: 文件pathimportsrcnewdatetimeosdir
2条回答

用户BenDundee正确地猜测到我无意中将XLSX文件重命名为XLS,并且看不到我面前的内容。在

而不是

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

试试看

^{pr2}$

这将保留以前的任何后缀,并且对文件名中的多个.字符是容错的。在

相关问题 更多 >