使用pyinstaller创建exe,但不打开文件



这是我的代码,我试图将其转换为。exe,它工作,但不打开和读取文本文件,我在MacOs上做了,工作得很好,但不工作在windows

问题出在这部分

def make_house():
try:
server_Adress = entry_server.get()
pythonpPort = int(entry_port.get())
playerName = entry_player.get()
mc = Minecraft.create(server_Adress, pythonpPort, playerName)
xp,yp,zp=mc.player.getPos()
print("yes")
# file_name = os.getcwd() + '/house.txt'
print("yes")
my_file = open("/Users/me/Desktop/Python/python-projects/house.txt","r")
print("yes")
print(my_file)
for line in my_file:
nums = line.strip().split(" ")
x = int(nums[0])  + xp
y = int(nums[1])  + yp
z = int(nums[2])  + zp
b = int(nums[3]) 
mc.setBlock(x, y, z, b)  
print("done")
except:
showerror(
"error", "please check your server address , port and player name")

我使用的命令:

pyinstaller filename.py——add-data 'pyramid.txt:。’——add-data’house.txt:。——window——onefile -i logo.ico

在你的pyinstaller命令中,你表明你想用你的应用程序编译house.txt文件,但是在代码中,你给了它一个绝对路径到你的用户Desktop的子目录。

如果您想使用可执行文件编译的文件,您需要创建一个相对路径到可执行文件在使用__file__属性执行时创建的运行时目录。

例如:

def make_house():
try:
server_Adress = entry_server.get()
pythonpPort = int(entry_port.get())
playerName = entry_player.get()
mc = Minecraft.create(server_Adress, pythonpPort, playerName)
xp,yp,zp=mc.player.getPos()
print("yes")
parent = os.path.dirname(__file__)  # parent is the runtime dir
file_name = os.path.join(parent, 'house.txt') # this is the file you compiled with the app
print("yes")
# my_file = open(file_name)
print("yes")
# print(my_file)
with open(file_name) as my_file:  # you should get into practice of opening files like this
for line in my_file:
nums = line.strip().split(" ")
x = int(nums[0])  + xp
y = int(nums[1])  + yp
z = int(nums[2])  + zp
b = int(nums[3]) 
mc.setBlock(x, y, z, b)  
print("done")
except:
showerror(
"error", "please check your server address , port and player name")

最新更新