文件准备
如图我要获取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获取文件路径内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论