【发布时间】:2020-02-25 15:51:33
【问题描述】:
我需要用给定采集路径的文件名保存一个文件。
给定一个 URL,我想解析它并提取文件名,这是我的代码...
我读取了一个 JSON 参数并将其提供给 Parse Url 函数。获取路径为字符串。
ParseUrl.py:
from urllib.parse import urlparse as up
a = up(jtp["AcquisitionPath"]) # => http://127.0.0.1:8000/Users/YodhResearch/Desktop/LongCtrl10min.tiff
print(a)
print(os.path.basename(a))
结果:
ParseResult(scheme='http', netloc='127.0.0.1:8000', path='/Users/YodhResearch/Desktop/LongCtrl10min.tiff', params='', query='', fragment='')
[....]
TypeError: expected str, bytes or os.PathLike object, not ParseResult
如您所见,解析 URL,但“LongCtrl10min.tiff”不在片段部分,而是全部在路径部分。为什么会这样?可能是因为“AcquisitionPath”是一个字符串,而 UrlParse 将所有这些都识别为唯一路径?
编辑:
a.path WORKS,我想知道为什么我不把它放到片段部分。
这是另一个例子:
from urllib.parse import urlparse as up
string = "http://127.0.0.1:8000/GIULIO%20FERRARI%20FOLDER/Giulio%20_%20CSV/Py%20Script/sparse%20python/tiff_test.tiff_IDAnal#1_IDAcq#10_TEMP_.json"
a = up(string)
print(a)
print(os.path.basename(a))
结果:
ParseResult(scheme='http', netloc='127.0.0.1:8000', path='/GIULIO%20FERRARI%20FOLDER/Giulio%20_%20CSV/Py%20Script/sparse%20python/tiff_test.tiff_IDAnal', params='', query='', fragment='1_IDAcq#10_TEMP_.json')
看,现在它没有得到应该是的正确片段:“tiff_test.tiff_IDAnal#1_IDAcq#10_TEMP_.json”
解决方案:
片段需要'#'符号!谢谢大家。
【问题讨论】:
-
试试
os.path.basename(a.path) -
它有效,但我想知道为什么我不把它放到片段部分
-
dont get it into fragment section是什么意思? -
因为 url 中的 fragment 格式为
http://127.0.0.1:8000/Users/YodhResearch/Desktop/LongCtrl10min.tiff#fragment -
您可能想要看到它,但您不会,因为文件名不是片段的一部分。片段开始以
#.
标签: python filenames urllib urlparse