我正在尝试将文件夹中的一组文件从.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
答案 0 :(得分: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"):
应该始终为true。
您混合了您的订单:
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.
答案 2 :(得分:0)
如果我理解正确,那么您目前将流程分为以下几个步骤:
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)
答案 3 :(得分:-1)
os.path.join
不会重命名文件。您应该使用os.rename
方法直接将其重命名,
os.rename(filename, filename[:-5]+'.xls')