-2

There is src folder witn env and main.py. I create log file like next and saw file in parent folder of src

from loguru import logger
logger.add("logs.txt")

enter image description here

In the other hand like this and file into src

dirname = path.dirname(__file__)
log_path = path.join(dirname, "logs.txt")
logger.add(log_path)

enter image description here

What is responsible to root folder when path is only filename? I need to create some files into src. I have copy-past code of dirname calculation to each of them. Looks like mistake.

Viewed
  • 1,159
  • 3
  • 16
  • 43
  • 1
    Maybe because you run your script from parent directory? Try to print the output of `os.getcwd()` – Corralien Sep 28 '21 at 19:50
  • @Corralien but `main.py` into `src` – Viewed Sep 28 '21 at 19:51
  • Are you asking why `logger.add("logs.txt")` adds a file in the parent directory? – Pranav Hosangadi Sep 28 '21 at 19:53
  • @PranavHosangadi why logger create file out of `src` folder when `main.py` into `src` – Viewed Sep 28 '21 at 19:54
  • 1
    Because all relative file paths are relative to the current working directory, which by default is the directory you ran your script from – Pranav Hosangadi Sep 28 '21 at 19:54
  • Before `logger.add` can you `print(os.getcwd())` to ensure where your script run from, please. If you run your code from spyder or pycharm or other tool, the working directory is the base of your project. – Corralien Sep 28 '21 at 19:55
  • @Corralien Can I set path to `src` for VS Code debug config? – Viewed Sep 28 '21 at 20:02
  • Try: [VSCode -- how to set working directory for debug](https://stackoverflow.com/questions/38623138/vscode-how-to-set-working-directory-for-debug). I think it's what your are looking for. – Corralien Sep 28 '21 at 20:06

1 Answers1

1

Here, the problem is how the working directory is set in your IDE (VSCode). Try to modify the working directory in the configuration:

VSCode -- how to set working directory for debug.

A more generic way could be:

import os

if DEBUG:
    os.chdir('./src')

logger.add("logs.txt")
Corralien
  • 109,409
  • 8
  • 28
  • 52