文件保存路径(Python)

Path for saving files (Python)

我正在尝试从 'D:\Study\Progs\test\samples' 获取文件,在将 .wav 转换为 .png 之后,我想将其保存到 'D:\Study\Progs\test\"input value"',但是在“name = os.path.abspath(file) 之后“程序采用了错误的路径“D:\Study\Progs\test\file.wav”而不是“D:\Study\Progs\test\samples\file.wav”。我能做什么呢? Here's my debug output And console output

import librosa.display
import matplotlib.pyplot as plt
import os


pa = "./"
save = pa+input()
os.mkdir(save)
for file in os.listdir("./samples"):
    if file.endswith(".wav"):
        print(file)
        name = os.path.abspath(file)
        ss = os.path.splitext(name)[0]+".png"
        print(name)
        audio = name
        x, sr = librosa.load(audio, mono=True, duration=5)
        save_path = os.path.join(save, ss)
        X = librosa.stft(x)
        Xdb = librosa.amplitude_to_db(abs(X))
        plt.figure(figsize=(20, 10))
        librosa.display.specshow(Xdb, sr=sr)
        plt.savefig(save_path)

如果您不介意按照@Andrew 的建议使用 pathlib,我认为您可以通过使用当前工作目录和每个 .wav 文件的主干来构建您想要做的事情.png 的文件名。

from pathlib import Path

cwd = Path.cwd()  # Current path.
sample_dir = cwd / "samples"  # Source files are here.

# Make some demo files if necessary.
if not sample_dir.exists():
    sample_dir.mkdir()
    (sample_dir / "file1.wav").touch()  # Make empty demo file.
    (sample_dir / "file2.wav").touch()  # Make empty demo file.

for file in sample_dir.glob("*.wav"):
    print(file)
    outfile = (cwd / file.stem).with_suffix(".png")
    print(f"->{outfile}")
    pass  # Replace this with whatever else needs to be done.

这是我的替代工作变体

import librosa.display
import matplotlib.pyplot as plt
import os
from pathlib import Path

cwd = Path.cwd()
print("Vvedite directoriu dlya sohraneniya resultatov:")
sf = input()
save_folder = cwd / sf
print("Vvedite nazvanie directorii s primerami .wav failov:")
smpl = input()
sample_dir = cwd / smpl
os.mkdir(save_folder)

for file in sample_dir.glob("*.wav"):
    print(file)
    base = os.path.basename(file)
    outfile = os.path.splitext(base)[0] + ".png"
    print(f"->{outfile}")
    audio = file
    x, sr = librosa.load(audio, mono=True, duration=5)
    save_path = os.path.join(save_folder, outfile)
    X = librosa.stft(x)
    Xdb = librosa.amplitude_to_db(abs(X))
    plt.figure(figsize=(20, 10))
    librosa.display.specshow(Xdb, sr=sr)
    plt.savefig(save_path)