'how to create a file in the code directory in python

I'm making this code that creates a file and writes on it, but i need this file do be created in the same folder that the .py file is located, because i'll need to send this to my profesor , so it need to be kinda of "customized" acording to where he'll download it. Currently, i'm working with this:

arquivo= open('C:\\Users\\cauej\\code\\PROJETO PY\\pedido.txt', 'w')

but i imagine that it wouldn't work on his computer, because it's using my director, but if the file were created in the same folder as the .py file, would work



Solution 1:[1]

You can use the answers from this question to get the path where the script is running, then use that path to write the file:

import os

dir_with_script = os.path.abspath(os.path.dirname(__file__))
path_to_file = os.path.join(dir_with_script, 'pedido.txt')

arquivo = open(path_to_file, 'w')
# ...

Solution 2:[2]

with getcwd() you can get the location of the .py file. Append the name of the output file to it:

import os directory = os.getcwd()

output_file_name = directory + "pedido.txt"

Solution 3:[3]

If you don't give an absolute path, python automatically works with the files in its current working directory. So you need to write something like this:

arquivo= open('pedido.txt', 'w')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfaccioni
Solution 2 Eduardo Lella
Solution 3