Python - 重命名文件

问题描述 投票:-3回答:4

我正在尝试将.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

python rename
4个回答
4
投票

如果我逐行阅读,我想

这是删除磁盘上文件的所有.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

另请注意,对于以小写if filename.endswith(".Xlsx"):结尾的所有文件,False可能是.xlsx

您可以使用操作系统的帮助,而不是[:-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


1
投票
  1. 通过你的全局调用,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.

0
投票

如果我理解正确,您目前正在按以下步骤划分流程:

  • 删除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)

-1
投票

os.path.join不重命名该文件。您应该使用os.rename方法直接重命名:

os.rename(filename, filename[:-5]+'.xls')
© www.soinside.com 2019 - 2024. All rights reserved.