簡體   English   中英

將處理后的文件名動態附加到輸出 txt 文件

[英]dynamically append processed filename to output txt file

樣本文件夾有一堆樣本a,b,c,d,e

在將最終輸出features_with_times保存到文件時,我希望它附加有它剛剛處理的文件的名稱。
我接近使用創建新文件,文件名包含循環變量 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:[Errno 2] 沒有這樣的文件或目錄:'mfcc_flwtssamples/abc.mp3.txt'

如何解決這個問題? 如何 _prevent samples/標簽介於兩者之間。 我知道我可以有names_to_append = [f for f in os.listdir(test_src)]這將保存 sample/ 文件夾中存在的文件的名稱。 到一個列表。

我如何將這些傳遞給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_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'
    )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM