0
Traceback (most recent call last):
  File "c:\Users\*\Documents\GitHub\_Testes\novo_teste.py", line 1, in <module>
    teste = open('teste.txt', 'w')
            ^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'teste.txt'

I don't understand why it doesn't create the file and instead returns this error

I already tried 'w', 'w+', 'x', 'x+'. It simply only accepts if I use the absolute path, shouldn't it accept using the script directory as a base?

I tried using 'os.getcwd()':

import os
print(os.getcwd())  # Show the actual directory
arquivo = open(os.getcwd()+"\\teste.txt", "w")
arquivo.write('teste')
arquivo.close()

result:

PS C:\Users\*\Documents\GitHub\_Testes> & C:/Users/*/AppData/Local/Programs/Python/Python311/python.exe c:/_Projetos/_Testes/testes.py
C:\Users\*\Documents\GitHub\_Testes
Traceback (most recent call last):
  File "c:\_Projetos\_Testes\testes.py", line 3, in <module>
    arquivo = open(os.getcwd()+"\\teste.txt", "w")
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\*\\Documents\\GitHub\\_Testes\\teste.txt'
Xzeroabs
  • 1
  • 1
  • 2
    I would expect it to create the `teste.txt` file in the directory you run the script from. Since it can't, there might be a problem with write permissions to that directory, or it has a strange name. In your error message the script seems to be getting run from `c:\Users\*\Documents`. Is * in the actual error message, or did you just use it to hide your username? – Adam Dec 11 '22 at 01:05
  • Welcome to Stack Overflow. Please check the linked duplicates. If they don't address the problem, at least make sure you understand how to check the *current working directory*, and thus get the needed information in order to understand what is going on. If there is still an issue then please try to create a [mre] (in this case, that would include steps for running the code). – Karl Knechtel Dec 11 '22 at 02:17
  • @Adam I already tried to create the file in another folder, changing the script and it gave the same error, the strangest thing is that a long time ago it worked normally, is it something from python 3.11? And yes I used * to hide the user, sorry – Xzeroabs Dec 12 '22 at 03:44

1 Answers1

-1

This is because from where you're calling (python novo_teste.py) it cannot find the file where you are (check if the path exist). You probably calling this from another directory. If you want understanding or visualize the actual directory, do this:

import os
print(os.getcwd()) # Show the actual directory
print(os.listdir()) # Show all files and folder on it
file = open("teste.txt", "w")
Samir
  • 1
  • 2