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)
相关推荐
2601_9628857212 分钟前
如何用 Python 计算终极振荡器(Ultimate Oscillator, UOS)?
开发语言·python
Thanks_ks17 分钟前
Python 列表与元组:可变性与不可变性的差异及使用场景选择
数据结构·python·列表·元组·可变对象·不可变对象·可哈希
benchmark_cc2 小时前
一次获取多只股票实时行情:QuantDash `quotes.get(symbols=[...])` 批量快照
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
geovindu2 小时前
python: PCA
开发语言·后端·python·算法
AI模型调用笔记2 小时前
流式 API 的 usage 为 null?用 cURL 看尾帧,别漏空 choices
python
天诰4 小时前
SA-T-06 轨迹数据工程 脏数据检测
人工智能·python·算法·语言模型·ai编程
Java后端的Ai之路5 小时前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
badhope5 小时前
Agent 说发布成功,文章却 404:我补了 4 张回读收据
后端·python·ai编程
xurileidian5 小时前
第 30 篇 · 边玩边学Python · 猜数字小游戏 把判断循环异常串起来
前端·python·算法
leeshuqing6 小时前
剪刀石头布-Python练习
python·游戏·优化·列表·字典·控制语句