python路径问题

在open函数中使用相对路径...总是提示文件不存在。于是便使用绝对路径了。

获取绝对路径的代码:

python 复制代码
        script_dir = os.path.dirname(os.path.abspath(__file__))
        self.parent_dir = os.path.dirname(script_dir)

python这个坑,挺害人的呀。记录下来,浪费了好多的时间。

Flask处理文件上传:

python 复制代码
@app.route('/upload', methods = ['POST'])
def save_file():
   if 'file' not in request.files:
      return 'No file part'
   file = request.files['file']
   if file.filename == '':
      return 'No selected file'
   if file:
      file.save(os.path.join("upload_folder", file.filename))
      return 'File ' + file.filename + ' successfully uploaded'

windows/linux文件锁:

python 复制代码
os_name = platform.system()
if os_name == "Windows":
    import msvcrt
    # 锁定文件
    msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 0)  # 锁定文件
    # 写入数据
    pickle.dump(global_resource, f)
    # 解锁文件
    msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 0)  # 解锁文件
else:
    import fcntl
    fcntl.flock(f, fcntl.LOCK_EX)
    pickle.dump(global_resource, f)
    fcntl.flock(f, fcntl.LOCK_UN)
相关推荐
用户019027581616 小时前
A 股到价提醒机器人:AlphaFeed + 飞书/钉钉 Webhook
python
特立独行的猫A6 小时前
Ionic + 仓颉语言的 cj-tauri 开发框架实战:开发精美移动端 APP
java·后端·python
高洁016 小时前
数据同化与动态状态估计:让孪生持续贴合现实
人工智能·python·深度学习·transformer·迁移学习
通信仿真爱好者7 小时前
第【139】期--基于深度学习的OFDM信道估计方法研究--python完整代码
python·深度学习·ofdm·信道估计
威哥爱编程7 小时前
模拟面试智能体开发实战 07:答完一题就点评一题,结构化输出给分建议,让每道题都变成复盘
python·agent·harmonyos
cpolar技术支持7 小时前
中文文件名排序跟拼音对不上:os.listdir 返回的是文件系统顺序,三个中文名按字节排结果正好相反
python·文件系统·cpolar·编码·排序
Thanks_ks7 小时前
【第 008 讲】在终端中运行 Python 程序:交互模式与脚本模式 | 绝对路径与相对路径 | 以模块方式运行 | 常见报错的识别与排查
python·异常处理·终端·脚本·命令行·cmd·python 解释器
威哥爱编程7 小时前
模拟面试智能体开发实战 08:总评报告先过三道闸,防泄题防夸大防错建议,才敢发到候选人手上
python·agent·harmonyos
郝学胜-神的一滴7 小时前
LangChain Skill 实现(渐进披露 On-Demand Skill,LangChain 官方 Deep Agent Skill 模式)
开发语言·python·langchain·numpy
投图匠18 小时前
十种不同风格的 CTP接口 框架
开发语言·python