首页 > 解决方案 > 如何在python中导入仅包含某些字符串的“dat”文件

问题描述

我正在尝试将几个“dat”文件导入 python spyder。

dat_file_list_images

这里列出了dat文件,列表中有两种以_1和_2结尾的类型。我只想导入以“_1”结尾的 dat 文件。

有没有办法通过一个循环一次导入它们?

导入它们后,我想将所有这些聚合到一个矩阵中。

标签: pythonpython-importspyder

解决方案


import os

files_to_import = [f for f in os.listdir(folder_path)
                  if f.endswith("1")]

Make sure that you know whether the files have a .dat-extension or not - in Windows Explorer, the default setting is to hide file endings, and this will make your code fail if the files have a different ending.

What this code does is called list comprehension - os.listdir() provides all the files in the folder, and you create a list with only the ones that end with "1".


推荐阅读