【问题标题】:Cannot write to file with specified path in Python [duplicate]无法在Python中写入具有指定路径的文件[重复]
【发布时间】:2021-07-18 05:30:45
【问题描述】:

我正在编写一个脚本来获取我当前的工作目录,将其连接到“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)

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

【问题讨论】:

  • 可能以r'/home/cameron..'开头
  • 使用os.getcwd() 查找当前工作目录。评论你得到了什么
  • 谢谢你们! Sid 你的解决方案奏效了。我相信“r”是一个错字,对吧?

标签: python file-io path


【解决方案1】:

path 可能需要为您的操作系统以 / 开头。

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

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

【讨论】:

    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2019-06-10
    • 2017-04-09
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多