python - 无法在 Python 中写入具有指定路径的文件
问题描述
我正在编写一个脚本来获取我当前的工作目录,将其连接到“cd”并将该字符串写入文件。但是,每当我尝试指定路径时,都会出现以下错误:
FileNotFoundError: [Errno 2] No such file or directory: 'home/cameron/projects/personal/new_window/last_directory.txt'
import os
import sys
from pathlib import Path
# Get working directory and transform into command string
stream = os.popen('pwd')
output = "cd " + stream.readline()
path = 'home/cameron/projects/personal/new_window/last_directory.txt'
# Open and write command to file
file = open(path,'w')
file.write(output)
file.close()
# Print status
print("Current Directory written:")
print(stream)
任何帮助将非常感激。我想写这个命令,这样当我深入文件树时,我可以保存它的位置,以防我需要打开另一个窗口。谢谢!
解决方案
path
可能需要从/
您的操作系统开始。
路径中的目录在写入之前也必须存在。如果它们尚不存在,您可以使用以下方法制作它们:
if not os.path.exists(path):
os.makedirs(path)
推荐阅读
- asp.net-core - GetObjectAsync() 不适用于 VS2019 版本 16.9.3 - 使用 AWSSDK.S3 版本 3.7.0.6 的 NET 5 应用程序
- ios - SwiftUI 中的 UITextField 导致“在视图更新期间修改状态,这将导致未定义的行为。”
- javascript - 如何对这些值进行异或?
- pygame - 不是键盘/鼠标的 Pygame 输入
- python - 如何从 micropython 中的字节数组/字节转换?
- python - 将上下文变量传递给表单
- node.js - 错误:函数预部署错误:命令以非零退出代码 1 终止
- sql-server - 用于列级加密的 SQL Server CA 证书
- visual-studio-code - 在 Visual Studio Code 扩展中动态添加/删除代码片段
- azure-devops - 如何在邮件正文中指定文件路径 - Azure devops 发送电子邮件任务