【问题标题】:reading and sorting files from a directory with for loop in python在python中使用for循环从目录中读取和排序文件
【发布时间】:2018-06-30 17:48:00
【问题描述】:

大家好, 我在一个目录中有 13 个 .npy 文件。其中一些以相同的名称开头。 示例:

B59_180322_153253.npy

B59_180322_173253.npy

B60_180324_153253.npy

B60_180324_173253.npy

B61_180324_173253.npy

B62_180324_173253.npy …… ....

我需要阅读它们并在 for 循环中连接以相同名称 (B59) 开头的那些,然后分配给字典数据。但是我找不到为此的自动化方法。 你有什么建议吗? >

数据 = {'B59':[], 'B62':[],

        'B65':[],

        'B67':[],

        'B68':[],

        'B79':[],

        'B80':[]}

当没有多个以相同名称开头的文件时,该代码运行良好。任何将不胜感激,在此先感谢。 最好的

对于 glob.glob("*.npy") 中的文件:

   experiment_id=file.split('_')[0]

   print(experiment_id)

   var = np.load(file)

  data[experiment_id]=var

【问题讨论】:

    标签: python file sorting concatenation


    【解决方案1】:

    非常感谢。

    遍历您的 txt 文件

    使用下面的代码,我可以使用具有文件名的键创建字典。所以我没有自己写。 但是当有 2 个以相同名称开头时,字典仍然只获取第一个 npy 文件。

    这个没有用,所以我删除了它并 数据[experiment_id].append(var)

    direc = os.getcwd() # Get current working directory
    text = '.npy' # Select your file delimiter
    
    file_dict = {} # Create an empty dict
    
    # Select only files with the ext extension
    txt_files = [i for i in os.listdir(direc) if os.path.splitext(i)[1] == ext]
    
    for f in txt_files:
       with open(os.path.join(direc,f)) as file_object:
       experiment_id=f.split('_')[0]
       print(experiment_id)
       file_dict[experiment_id]=np.load(f)
    

    你觉得这里可以添加什么?

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2016-02-22
      • 1970-01-01
      相关资源
      最近更新 更多