今天在使用 Pyinstaller
打包包含 Pathlib
的文件时报错。
这是源代码:
这是个修改当前文件夹下的图片格式的 exe。
# -*- coding:utf8 -*-
from pathlib import Path
from PIL import Image
import sys
path = Path(__file__).parent
for img_path in path.glob('*[!.exe]'):
img = Image.open(img_path)
img1 = img.convert('L')
img2 = img1.resize((128, 128))
img2.save(img_path.parent / img_path.name)
原因是因为我在文件里使用了 Path(__file__)
,在搜索了很多资料后,才找到一个解决办法。
import sys
path = Path(sys.argv[0])
使用 sys
这个库就可以获取脚本的绝对路径了。
# -*- coding:utf8 -*-
from pathlib import Path
from PIL import Image
import sys
path = Path(sys.argv[0]).parent
for img_path in path.glob('*[!.exe]'):
img = Image.open(img_path)
img1 = img.convert('L')
img2 = img1.resize((128, 128))
img2.save(img_path.parent / img_path.name)