如何从numpy文件的名称创建一个numpy名称列表

时间:2017-03-29 14:06:17

标签: python numpy

我有一组numpy文件,它们位于一个文件夹中。 我需要创建一个numpy列表,我可以在每行中放入有关每个文件名的详细信息:

实施例: 文件名:

AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy

我列表中的每一行都必须包含:

300001 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667 

我的意思是我只需要放数字然后空格。

我使用此方法,但它提供了我的文件的所有名称。

import os
path_For_Numpy_Files = 'C:\\Users\\user\\My_Test_Traces\\1000_Traces_bin'
path_List_File='C:\\Users\\user\\My_Test_Traces\\NewTest.list_bin'
os.chdir(path_For_Numpy_Files)
list_files=os.listdir(os.getcwd())
with open(path_List_File, 'w') as fp:
    fp.write('\n'.join(sorted((list_files),key=os.path.getmtime)))

我可以更正它给我等待的结果吗?

2 个答案:

答案 0 :(得分:0)

这似乎是基本的想法。

from pathlib import Path
import re

p = Path('c:/scratch/sample')
for fileName in p.iterdir():
    print (fileName.name)
    print (' '.join(re.findall('=([0123456789abcdef]{2,})', fileName.name)))

此脚本的输出为:

AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
300001 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667
AES_Trace=300002_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
300002 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667
AES_Trace=300003_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
300003 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667

答案 1 :(得分:0)

你可以试试这个:

 def reformat_name(old):
        key0=  old.split('_key=')[1].split('_Plaintext=')[0]
        key1 = old.split('_Plaintext=')[1].split('_Ciphertext=')[0]
        key2 = old.split('_Ciphertext=')[1].split('.bin')[0]
        name = old.split('AES_Trace=')[1].split('_key=')[0]
        #new_filename =  '{:07d}'.format(int(name)) + '    ' + key0 + '    ' + key1 + '    '+ key2 + '    '
        new_filename = '{:07d}'.format(int(name)) + '    ' + key0 + '    ' + key1 + '    '+ key2 + '    '
        return new_filename

    import os
    path_For_Numpy_Files='C:\\Users\\user\\My_Test_Traces\\3_Traces_npy'
    path_List_File='C:\\Users\\user\\My_Test_Traces\\ttttttTest.list_npy'
    os.chdir(path_For_Numpy_Files)
    list_files_Without_Sort=os.listdir(os.getcwd())
    list_files_Sorted=sorted((list_files_Without_Sort),key=os.path.getmtime)
    with open(path_List_File, 'w') as fp:
        for file in list_files_Sorted:
            new_name = reformat_name(file)
            fp.write(new_name+ '\n')