# 打包路径测试
import os
import sys
import time
def base_path(path):
if getattr(sys, 'frozen', None):
basedir = sys._MEIPASS
else:
basedir = os.path.dirname(__file__)
return os.path.join(basedir, path)
tmd = base_path('') # 这是解压路径
cwd = os.getcwd() # 这是程序的所在路径
# 当需要调用打包的外部文件时
# os.chdir(tmd) # 先把工作路径变成解压路径
# 当需要写出文件到程序所在目录时
# os.chdir(cwd) # 把工作路径切换回来
name_dir = 'name'
age_dir = 'age'
# 生成age name两个文件夹 无问题
if not os.path.exists(age_dir):
os.mkdir(age_dir)
# os.chdir(cwd)
# 创建多个目录
dirs_to_create = ['age/age01', 'age/age02']
for d in dirs_to_create:
# print("d------",d)
# new_dir = os.path.join('/', d)
os.makedirs(d, exist_ok=True)
print(f'Created directory: {d}')
with open('age/age02/age001.txt', 'w') as f:
f.write('Hello, world_1!\n')
with open('age/age02/age002.txt', 'w') as f:
f.write('Hello, world_2!\n')
# 读写文件
os.chdir(tmd) # 调用
with open("name/name输入.txt", "r") as f1:
os.chdir(cwd) # 写
with open("age/age02/name输出.txt", "w") as f2:
for line in f1:
f2.write(line)
time.sleep(5)
# 删除文件
filename = 'age/age02/age001.txt'
if os.path.exists(filename):
os.remove(filename)
print(f'Removed file: {filename}')
else:
print(f'File not found: {filename}')
打包路径测试.exe
最新推荐文章于 2024-07-21 18:33:37 发布