首页 > 解决方案 > 无法在 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)

任何帮助将非常感激。我想写这个命令,这样当我深入文件树时,我可以保存它的位置,以防我需要打开另一个窗口。谢谢!

标签: pythonfile-iopath

解决方案


path可能需要从/您的操作系统开始。

路径中的目录在写入之前也必须存在。如果它们尚不存在,您可以使用以下方法制作它们:

if not os.path.exists(path):
     os.makedirs(path)

推荐阅读