【问题标题】:Append Excel Files in Multiple Directories in Python在 Python 中将 Excel 文件附加到多个目录中
【发布时间】:2021-06-09 18:31:30
【问题描述】:

我的目标是将存在于不同目录中的 9 个 excel 文件附加在一起。我有一个具有以下结构的目录树:

Big Folder
|
├── folder_1/
|   ├── file1.xls
|   ├── file2.xls
|   └── file3.xls
|
├── folder_2/
|   ├── file4.xls
|   ├── file5.xls
|   └── file6.xls
|
├── folder_3/
|   ├── file7.xls
|   ├── file8.xls
|   └── file9.xls

我成功编写了一个循环,将file1file2file3 一起附加到folder_1 中。我的想法是将此循环嵌套到另一个循环中,该循环作为列表流经每个文件夹。我目前正在寻找我们os.walk 来完成此任务,但在folder_1 中遇到以下错误

[Errno 2 没有这样的文件或目录]

社区成员是否有关于如何扩展此循环以在每个目录中执行的建议?谢谢!

【问题讨论】:

    标签: python excel operating-system nested-loops


    【解决方案1】:

    如果没有给出某种代码可以使用,我很难知道你是如何实现程序的,但是我相信你误用了os.walk() 方法,请阅读它here

    我将使用os.walk() 方法以下列方式获取当前目录和子目录中各种文件的路径。

    import os    
    all_files = [(path, files) for path, dirs, files in os.walk(".")]
    

    然后像这样获取所有以“*.xls”结尾的文件

    all_xls_files = [
        os.path.join(path, xls_file)
        for (path, xls_files_list) in all_files
        for xls_file in xls_files_list
        if xls_file.endswith(".xls")
    ]
    

    这相当于

    all_xls_files = []
    for (path, xls_files_list) in all_files:
        for xls_file in xls_files_list:
            if xls_file.endswith(".xls"):
                files.append(os.path.join(path, xls_file))
    

    一旦你获得一个包含路径的 excel 文件列表 你可以打开它们

    with open("my_output_file", "w") as output_file:
        for file in all_xls_files:
            with open(file) as f:
                # Do your append here
          
    

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多