Trying to write data to a file like this:

f = open('test.txt', 'w') f.write("test") f.close() with open('test.txt', 'w') as f: f.write("test") 

The first method and the second one do not give any results; I run the script in this way E:\cript.py

I understand correctly that I should appear in the same directory, where is the script itself, the new file named test? Why it doesn’t appear, it seems to be right, there are no errors in the console ...

upd: file was created manually, assigned rights for everyone to everything, but the text does not appear in it

  • 2
    And he still started? And the file will be created in the directory in which you are located at the time of launch (most likely your home directory) - Alexey Ten
  • everything works as it should - Enikeyschik
  • @AlexeyTen, yes, you are right, the files were not created where the script was, but in the directory from which I ran it. Is it possible to somehow rewrite the script so that it creates files in the directory where it is located? - alexey romashev 2:53 pm

1 answer 1

To create a file in the folder where the script is located, you need to 1) get the path to the folder, and 2) add it to the file name:

 import os folder = os.path.dirname(os.path.abspath(__file__))) # папк, где лежит скрипт filepath = os.path.join(folder, "test.txt") # создаем абсолютный путь к файлу # далее как обычно f = open(filepath, 'w')