Python重命名fi

2024-04-24 14:58:30 发布

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

我正在尝试将文件夹中的一组文件从.Xlsx重命名为.xls。这就是我迄今为止所做的:

allFiles = glob.glob("/*.Xlsx") # Folder that has all the files
renamed = []
for filename in allFiles:
    if filename.endswith(".Xlsx"):
        os.rename(filename, filename[:-5])
        renamed.append(filename[:-5]) # removed the .Xlsx extension
        os.path.join(renamed, '.xls') # this fails

我想知道如何将.xls添加到上面的列表renamed


Tags: 文件the文件夹thatosfolderallfilename
3条回答
  1. 对于glob调用,if filename.endswith(".Xlsx"):应该始终为真。

  2. 你把订单弄混了:

    os.rename(filename, filename[:-5])  # this renames foo.Xlsx to foo, everything after it is too late.
    renamed.append(filename[:-5]) # This adds the file w/o the extension, but also w/o the new extension.
    os.path.join(renamed, '.xls') # This is a statement which would produce a result if called correctly (i. e. with a string instead of a list), but the result is discarded.
    

    相反,你应该这样做

    basename = filename[:-5]
    newname = os.path.join(basename, '.xls')
    os.rename(filename, newname)
    renamed.append(basename) # or newname? Choose what you need.
    

如果我理解正确的话,您当前将流程划分为以下步骤:

  • 卸下xlsx扩展插件
  • 将文件添加到列表(不带扩展名)
  • 将新扩展名添加到文件中(此操作失败,因为os.path.join不会将列表作为输入)

为了使它更简单,我只会重命名为新的扩展名,如果您需要renamed列表,请填充它。像这样:

allFiles = glob.glob("/*.Xlsx") <- Folder that has all the files
renamed = []
for filename in allFiles:
    if filename.endswith(".Xlsx"):
        new_name = filename[:-5]+'.xls'
        os.rename(filename, new_name)
        renamed.append(new_name)

如果我逐行读的话,我想

这将删除磁盘上文件的所有.xlsx扩展名

os.rename(filename, filename[:-5])         # Problem 1

然后将不带扩展名的名称添加到列表中

renamed.append(filename[:-5])

然后尝试连接a)整个数组和b)一个文件及其扩展名,而不是两条路径

os.path.join(renamed, '.xls')             # Problem 2 and 3

你宁愿

newname = filename[:-5]                  # remove extension
newname = newname + ".xls"               # add new extension
os.rename(filename, newname)             # rename correctly
renamed.append( ... )                    # Whatever name you want in the list

还要注意,对于以小写.xlsx结尾的所有文件,if filename.endswith(".Xlsx"):可能是False。你知道吗

除了[:-5],您还可以使用操作系统的帮助:

import glob
import os

allFiles = glob.glob("c:/test/*.xlsx")
renamed = []
for filename in allFiles:
    path, filename = os.path.split(filename)
    basename, extension = os.path.splitext(filename)
    if extension == ".xlsx":
        destination = os.path.join(path, basename+".xls")
        os.rename(filename, destination)

仅供参考:如果重命名是程序的唯一目的,请在Windows命令提示符下尝试ren *.xlsx *.xls。你知道吗

相关问题 更多 >