代码之家  ›  专栏  ›  技术社区  ›  kRazzy R Avaris

将处理过的文件名动态附加到输出txt文件

  •  1
  • kRazzy R Avaris  · 技术社区  · 7 年前

    样品 文件夹中有一组示例 a,b,c,d,e .

    保存最终输出时 features_with_times 对于一个文件,我希望它附加上刚刚处理的文件的名称。
    我使用 Creating a new file, filename contains loop variable, python ,我执行了以下操作,但出现了小错误。

    from __future__ import division
    
    import librosa
    import os
    import numpy as np
    
    
    test_src = 'samples/'
    
    path_to_audios = [os.path.join(test_src, f) for f in os.listdir(test_src)]
    
    for audio_path in path_to_audios:
        # blah ..
        # blah 
    
        # blah . . 
        # blah  . . 
    
    
        features_with_times= some_val 
        # np.savetxt('koo'+ str(k) + '.txt')
    
        print "saving mfcc features"
        np.savetxt('mfcc_flwts'+str(audio_path)+'.txt', features_with_times,newline ='\n', delimiter= '\t')
    

    错误 :IOError:[错误号2]没有这样的文件或目录:“mfcc\U flwtssamples/abc”。mp3.txt'

    如何修复此问题?如何防止 samples/ 从中间进入标签。 我知道我可以 names_to_append = [f for f in os.listdir(test_src)] 将保存样本/文件夹中存在的文件的名称。添加到列表。

    如何将这些传递给 np.savetxt()

    新手问题。

    更新: 我想到的原始解决方案是减去两个字符串:

    a = 'samples/'
    b = audio_path
    val = b.replace(a,'')
    np.savetxt('mfcc_flwts_'+str(val)+'.txt', features_with_times,newline ='\n', delimiter= '\t')
    

    是否有更好的方法来实现我的解决方案。

    更新:2:

    我还可以将其保存到我选择的文件夹中,如下所示:

    save_destination = 'outputss/'
        np.savetxt(os.path.join(save_destination,'mfcc_flwts_'+str(val)+'.txt'), features_with_times,newline ='\n', delimiter= '\t')
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   ascripter    7 年前

    你的问题是 path_to_audios 包含中文件的相对路径 samples/<filename> ,而不仅仅是文件名。一个想法是稍微更改一下循环,以便在循环中只获得可用的文件名:

    test_src = 'samples/'
    
    filenames = os.listdir(test_src)
    path_to_audios = [os.path.join(test_src, f) for f in filenames]
    
    for fn, audio_path in zip(filenames, path_to_audios):
        # now you've got path and filename in parallel. If you need to discard the file ending since it's not ".txt",
        # split at the dot and take the first part only
        fn = fn.split('.')[0]
    
        print "saving mfcc features"
        np.savetxt('mfcc_flwts'+str(fn)+'.txt', features_with_times,newline ='\n', delimiter= '\t')
    

    最后一行将结果保存在工作目录中,这也是编写文件名的糟糕方式。所以我们想把它改成。。。

        np.savetxt(
            os.path.join(your_target_path, 'mfcc_flwts{0}.txt'.format(fn)),
            features_with_times,
            newline ='\n',
            delimiter= '\t'
        )