py 这将读取放置在同一文件夹中的文本文件,我已经使用 pyinstaller 创建了
,main_file.spec
和 main_file.exe
文件 -- onefile main_File.pymain_file.exe
文件是在dist文件中创建的。当我尝试运行 main_file.exe
应用程序时,出现无法找到指定文件的错误。
我尝试通过添加 datas= [('data.txt','.')]
来修改我的 main_file.spec
但确实有效,请帮助我。主要问题是我不想将 data.txt
和 main_file.exe
放在单个文件夹中。当我运行 main_file.exe
时,它应该读取 data.txt
文件
我的 main_file.py
import os
import os.path
import shutil
def main():
d = os.getcwd() #Gets the current working directory
print(d)
os.chdir("..") #Go up one directory from working directory
o = [os.path.join(d,o) for o in os.listdir(d) if
os.path.isdir(os.path.join(d,o))] # Gets all directories in the tuple
print(o)
for item in o:
if os.path.exists(item + '\\data.txt'):
file = item + '\\data.txt'
input('Enetr any to read file')
f = open(file)
print(f.read())
if __name__ == '__main__':
main()
input('Enter any key to close')
还有我的规范文件
# -*- mode: python -*-
block_cipher = None
a = Analysis(['Project_Main_File.py'],
pathex=['E:\\Python coding\\File_Read'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='Project_Main_File',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
最佳答案
好的,所以首先 - 如果您尝试读取文件 data.txt
但文件名为 main_file.spec
它根本找不到它, 这不是同一个文件。
如果您想在转换为 exe 之前阅读 data.txt
但在转换之后阅读 main_file.spec
,我会建议您使用 try: catch:
所以它'将尝试读取 data.txt
文件,但如果它不存在,请读取 main_file.spec
。
其次 - 你不必将文件放在同一个文件夹中,但相对路径需要始终准确,顺便说一句,我不确定你是否必须使用 os 来使用相对路径,但也许它只是在 python3 上。
如果您希望文件位于相邻文件夹中,您可以执行以下操作:
filepath = "../data/main_file.spec" # one directory up, one down to data, and to the file
with open(filepath) as f:
print(f.read())
应该就这样了,记得把文件放在正确的相对路径下。 并使用 try catch:
filetxt = "../data/data.txt" # one directory up, one down to data, and to the file
filespec = "../data/main_file.spec" # one directory up, one down to data, and to the file
try:
with open(filetxt) as f:
print(f.read())
catch:
with open(filespec) as f:
print(f.read())
应该是吧!
关于python - 如何读取 main_file.exe 中的 data.txt 而不将它们保存在 python 中的单个文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54251782/