0

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

3 Answers 3

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')
# ...
Sign up to request clarification or add additional context in comments.

Comments

0

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"

1 Comment

import os and directory = os.getcwd() should be in two lines, sorry
0

In your case, you gave an absolute path, which starts from C:\ drive and includes all the parent folders of the file. It always works and mentions the same file, no matter where you are currently locating.

There is also a relative path which can be given by telling the path, that starts from the directory you are currently in. You can assume that it automatically uses path of current working directory as a prefix and generates an absoulte path, like this current working directory + given path to file.

So I guess you need to write like this:

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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.