Search code examples
pythonrelative-path

How to use Relative paths in python with, "with open()" and windows cmd or powershell


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


Solution

  • 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: