我基本上试图通过一堆excel .xls文件迭代,并将它们更改为。xlsx文件,我真的不知道从这里去哪里。感觉我把代码弄得一团糟。
我得到以下错误:TypeError: listdir:路径应该是字符串,字节,os。PathLike或None,不是list
所以我对代码做了一些改动,它可能会去某个地方。我编辑了下面的代码。
file_path = Path.home().joinpath("Desktop", "test")
excel = win32.gencache.EnsureDispatch('Excel.Application')
if __name__ == "__main__":
while True:
the_path = (str(file_path) + str("\"))
print(the_path)
os.chdir(the_path)
xls_files = os.listdir('.')
print(xls_files)
for downloadedFile in listdir(xls_files):
if downloadedFile.endswith('.xls'):
wb = excel.Workbooks.Open(xls_files)
pyexcel.save_book_as(downloadedFile, FileFormat = 51)
downloadedFile.Close()
downloadedFile.Save()
excel.Application.Quit()
我真的不知道我写的代码是否有意义。如果有人能帮我弄清楚,至少我在正确的轨道上,我会很好。
谢谢你的帮助!
pyexcel
似乎是这个任务的正确工具。
-
Install three packages
pip install pyexcel pyexcel-xls pyexcel-xlsx
-
运行如下脚本:
from pathlib import Path import pyexcel as p # Find your home path by print out `Path.home()` # Then add additional path that points to the folder that # contains all the .xls files. # We are essentially using absolute path here, but change # it to relative path if necessary. folder = Path.home().joinpath('Desktop/test') # Iterate all the files inside the folder. # Pick the .xls file only and convert it to .xlsx file # The converted file will have the same name. # E.g. foo.xls will be converted to foo.xlsx for file in folder.iterdir(): if '.xls' in file.suffix: book = p.get_book(file_name=str(file)) book.save_as(file.stem + '.xlsx')
注意:
- 该脚本仅在macOS中测试过,但没有在Windows中测试过。为了满足Windows中的文件系统,可能需要进行一些具体的调整。但是,
pathlib
应该能够处理Windows的特性。 - 如果有特殊需要,可以调整脚本