Python脚本执行报错:文件路径中出现多余的'b'字符
问题:文件路径出现多余"b"字符导致加载失败
运行代码时出现如下报错:
Could not load source layer for INPUT: G:\Dropbox\temp\worklayers\b'hej0.tif' not found
相关代码片段:
# %% Definitions path_root = normpath(r'G:\Dropbox\temp\') path_start = normpath(r'G:\Dropbox\temp\worklayers\') path_temp = normpath(r'G:\Dropbox\temp\templayers\') path_temp2 = normpath(r'G:\Dropbox\temp\temp2layers\') path_end = normpath(r'G:\Dropbox\temp\resultlayers\') path_doc = normpath(r'G:\Dropbox\Documents\') directory = os.fsencode(path_start) df = pd.read_csv(path_doc+'\\DEM_masterfile.csv') slope_list = [4, 4.9, 5.9, 7.1, 8.2, 10, 11.8, 13.8, 15.7, 17.9, 20.6, 25] aspect_list_1 = [[0, 15], [15,30], [30, 45], [45, 60], [60, 75], [75, 90], [90, 105], [105, 120], [120, 135], [135, 150], [150, 165], [165, 180]] aspect_list_2 = [[180, 195], [195, 210], [210, 225], [225, 240], [240, 255], [255, 270], [270, 285], [285, 300], [300, 315], [315, 330], [330, 345], [345, 360]] # %% Generating the slope and aspect vector files from the DEM raster for number in os.listdir(directory): processing.run("native:slope", {'INPUT':path_start+'\\'+str(number),'Z_FACTOR':1,'OUTPUT':path_temp+'\\'+'slope_'+str(number)}) processing.run("native:aspect", {'INPUT':path_start+'\\'+str(number),'Z_FACTOR':1,'OUTPUT':path_temp+'\\'+'aspect_'+str(number)})
原因分析
报错里的"b"来自字节串的字符串转换:
os.fsencode(path_start)会把路径转成字节串(bytes类型)os.listdir(directory)遍历返回的每个number都是字节串对象,比如b'hej0.tif'- 当你用
str(number)转换时,Python会把字节串的表示形式转成字符串,也就是直接带上b'...'的格式,拼接路径后就出现了多余的"b"。
解决方案
有两种可行的修复方式:
方式1:直接遍历字符串路径(推荐)
去掉os.fsencode,直接用原始字符串路径遍历,得到的文件名本身就是字符串:
# 移除os.fsencode相关代码,直接遍历path_start for filename in os.listdir(path_start): # 用os.path.join拼接路径,避免手动加斜杠的问题 input_path = os.path.join(path_start, filename) slope_output = os.path.join(path_temp, f'slope_{filename}') aspect_output = os.path.join(path_temp, f'aspect_{filename}') processing.run("native:slope", {'INPUT': input_path, 'Z_FACTOR':1, 'OUTPUT': slope_output}) processing.run("native:aspect", {'INPUT': input_path, 'Z_FACTOR':1, 'OUTPUT': aspect_output})
方式2:解码字节串为字符串
如果必须保留os.fsencode,需要把遍历到的字节串解码成正常字符串:
directory = os.fsencode(path_start) for number in os.listdir(directory): # 把字节串解码为字符串(编码格式可根据系统调整,一般用utf-8即可) filename = number.decode('utf-8') input_path = os.path.join(path_start, filename) slope_output = os.path.join(path_temp, f'slope_{filename}') aspect_output = os.path.join(path_temp, f'aspect_{filename}') processing.run("native:slope", {'INPUT': input_path, 'Z_FACTOR':1, 'OUTPUT': slope_output}) processing.run("native:aspect", {'INPUT': input_path, 'Z_FACTOR':1, 'OUTPUT': aspect_output})
额外建议:尽量用
os.path.join拼接路径,比手动加\\更可靠,也能适配不同操作系统的路径分隔符。
内容的提问来源于stack exchange,提问作者Tobias Bowley
相关产品推荐
相关产品推荐

