如何使用open()使用Python中的相对路径和Windows CMD或PowerShell

发布于 2025-02-10 13:22:22 字数 473 浏览 0 评论 0原文

这是我的代码:

from datetime import datetime

now = datetime.now()
date_time = now.strftime("%d-%m-%Y-%H-%M")
with open("Keyboard\Program\log\_temp.txt", "w") as f:
    f.write(f"Keyboard\Program\log\log-{date_time}.txt")

我试图在Windows CMD或PS中执行此操作,但我得到的只是

打开(“键盘\ program \ log_temp.txt”,“ w”)为f: FILENOTFOUNDERROR:[ERRNO 2]没有这样的文件或目录: '键盘\ program \ log \ _temp.txt'

我也尝试了Stackoverlow的不同解决方案,但似乎没有帮助我

Here is my code:

from datetime import datetime

now = datetime.now()
date_time = now.strftime("%d-%m-%Y-%H-%M")
with open("Keyboard\Program\log\_temp.txt", "w") as f:
    f.write(f"Keyboard\Program\log\log-{date_time}.txt")

im trying to execude this in my windows cmd or ps but all i get is

with open("Keyboard\Program\log_temp.txt", "w") as f:
FileNotFoundError: [Errno 2] No such file or directory:
'Keyboard\Program\log\_temp.txt'

I also tried different solutions from stackoverlow but noething seemed to help for my

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冬天旳寂寞 2025-02-17 13:22:22

如果您的CWD是:e:\@codingGameEngine \!projects \ pythonProjects \ randomprojects \ randomprojects \ keyboard \ jeconboard \ program,那么您只需要与之相关:

with open("log\_temp.txt", "w") as f:

If your cwd is: E:\@CodingGameEngine\!Projects\PythonProjects\RandomProjects\Keyboard\Program then you only need to be relative to that:

with open("log\_temp.txt", "w") as f:
甜中书 2025-02-17 13:22:22

总体而言,程序不知道或关心他们的可执行生命。当您运行它们时,您将从某些工作目录启动它们,并且所有相对路径名都从那里解释。

从命令行启动程序时,很容易看到您当前的工作目录是什么(在PowerShell或Bash中运行PWD,或CMD中的CD)。但是,当您通过双击图标启动程序时,Windows将当前的工作目录更改为包含程序的工作目录。这就是为什么容易混淆并认为相对路径始终与包含程序的文件夹相对的原因。

如果您正在写一些要从命令行运行的内容,则可能需要写它以使用绝对路径,而不是假设用户将成为您认为的位置。如果您希望用户能够配置它,则可以随时从环境变量获取路径。

Programs, in general, don't know or care where their executable lives. When you run them, you are starting them from some working directory, and all relative pathnames are interpreted from there.

When you start a program from the command line, it's easy to see what your current working directory is (Run pwd in PowerShell or bash, or cd in CMD). When you start a program by double-clicking an icon, however, Windows changes the current working directory to the one containing the program. That's why it's easy to get confused and think relative paths are always relative to the folder containing the program.

If you're writing something to be run from the command-line, you might want to write it to use absolute paths instead of assuming the user will be where you think they are. You can always get the path from an environment variable if you want the user to be able to configure it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文