Python实现迅速获取文件的路径
文件准备

如图我要获取get_path的绝对路径,以及下方MP3文件的绝对路径
代码准备
1.获取当前工作目录的绝对路径
import os
# 获取当前工作目录的绝对路径
current_directory = os.getcwd()
print("当前工作目录的绝对路径是:", current_directory)
运行结果

2.获取指定文件的绝对路径
import os
# 获取当前工作目录的绝对路径
current_directory = os.getcwd()
filepath="006-get_path\mp3\Swag _ Miyauchi _ Audio.mp3"
print("当前工作目录的绝对路径是:", current_directory+filepath)
运行结果

我要获得MP3下的swag……文件的路径,那么我先打印出绝对路径current_dictory然后加上 \006-get_path\mp3\Swag _ Miyauchi _ Audio.mp3即可

打印成功
应用
# 使用示例
if __name__ == "__main__":
# 设置要转换的格式,支持mp3, wav, ogg, flac等格式
input_format = "mp3"
output_format = "wav"
# 单文件转换示例
input_file_path = "D:/400-File/000-Project/000-Pycharm/005-CSDN_File/005-convert_music/mp3/Joel Adams - Please Don't Go (Official Music Video).mp3"
output_file_path = "D:/400-File/000-Project/000-Pycharm/005-CSDN_File/005-convert_music/wav/Joel Adams - Please Don't Go (Official Music Video).wav"
converter = AudioConverter(input_format, output_format)
converter.convert(input_file_path, output_file_path)比如此处代码我们要插入冗长的路径,这样如果是多文件的话

将会十分的麻烦
所以我们修改代码为
import os
# 获取当前工作目录的绝对路径
current_directory = os.getcwd()
filepath1="/005-convert_music/mp3/Joel Adams - Please Don't Go (Official Music Video).mp3"
filepath2="/005-convert_music/wav/Joel Adams - Please Don't Go (Official Music Video).wav"
filefullpath1=current_directory+filepath1
filefullpath2=current_directory+filepath2
print(filefullpath1)
print(filefullpath2)
# 使用示例
if __name__ == "__main__":
# 设置要转换的格式,支持mp3, wav, ogg, flac等格式
input_format = "mp3"
output_format = "wav"
# 单文件转换示例
input_file_path = filefullpath1
output_file_path = filefullpath2
converter = AudioConverter(input_format, output_format)
converter.convert(input_file_path, output_file_path)使用os.getcwd()获取绝对路径,免去繁杂的路径,这样我们就能快速得到文件的路径了
需要注意的是,我们获取的是文件的绝对路径

为了得到Joel Adams - Please Don't Go (Official Music Video).mp3的路径,我们需要加上
“/005-convert_music/mp3/Joel Adams - Please Don't Go (Official Music Video).mp3”
具体的代码就是这样的
import os # 获取当前工作目录的绝对路径 current_directory = os.getcwd() filepath1="/005-convert_music/mp3/Joel Adams - Please Don't Go (Official Music Video).mp3" filefullpath1=current_directory+filepath1
获取绝对路径后将两个路径相加即可
仅仅是两个文件的路径也许不明显,但是如果是成白上千的文件,那么如此获得的路径将会节约许许多多的时间
到此这篇关于Python实现迅速获取文件的路径的文章就介绍到这了,更多相关Python获取文件路径内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python图像处理之直线和曲线的拟合与绘制【curve_fit()应用】
这篇文章主要介绍了Python图像处理之直线和曲线的拟合与绘制,结合实例形式分析了Python曲线拟合相关函数curve_fit()的使用技巧,需要的朋友可以参考下2018-12-12
From CSV to SQLite3 by python 导入csv到sqlite实例
今天小编就为大家分享一篇From CSV to SQLite3 by python 导入csv到sqlite实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-02-02
python实现sm2和sm4国密(国家商用密码)算法的示例
这篇文章主要介绍了python实现sm2和sm4国密(国家商用密码)算法的示例,帮助大家使用python加密文件,感兴趣的朋友可以了解下2020-09-09


最新评论