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

Python 将处理后的文件名动态附加到输出txt文件,python,numpy,save,Python,Numpy,Save,samples文件夹中有一组示例a、b、c、d、e 将最终输出的features\u和_times保存到文件中时,我希望将其附加到刚刚处理的文件的名称中。 我尝试使用,我做了以下操作,但得到了一个小错误 from __future__ import division import librosa import os import numpy as np test_src = 'samples/' path_to_audios = [os.path.join(test_src, f) fo

samples文件夹中有一组示例
a、b、c、d、e

将最终输出的
features\u和_times
保存到文件中时,我希望将其附加到刚刚处理的文件的名称中。
我尝试使用,我做了以下操作,但得到了一个小错误

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:[Errno 2]没有这样的文件或目录:“mfcc_flwtssamples/abc.mp3.txt”

如何解决这个问题?如何防止
samples/
标记介于两者之间。 我知道我可以有
name\u to\u append=[f for f in os.listdir(test\u 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')

您的问题是
path\u to_audios
包含
samples/
中文件的相对路径,而不仅仅是文件名。一个想法是稍微更改一下循环,这样循环中就只有可用的文件名:

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'
    )

您希望的文件名/文件路径是什么?如果
samples
文件夹中有audios
a
b
c
。经过处理后,np.savetxt的输出应该是
mfcc_flwts_a.txt
mfcc_flwts_b.txt
mfcc_flwts_c.txt
,这样我就知道哪个文件是从哪个文件生成的。一种简单的方法是两个字符串相减,比如:
a='samples/'
>b='samples/aa.mp3'
>b.replace(a),”
'aa.mp3'
并将此^?现在他们只是被保存到工作目录你是个救命恩人!请你在这里说明一下: