3

I am trying to create a file in the folder I running my .py script. This is the code I am using. The problem is that the open function requires / for directories. new_file_path uses \ instead. This is causing the open function to fail. How do I fix this?

import os

dir_path = os.path.dirname(os.path.realpath(__file__))
new_file_path = str(os.path.join(dir_path, 'mynewfile.txt'))
open(new_file_path, "x") 
2
  • no need to use str() function on the result from os.path.join(). And post full traceback you get. There is no problem with using forward slash in path Commented Mar 15, 2020 at 11:56
  • There's no need for all that... The default will be the current working dir so a simple open('mynewfile.txt', 'w') will do the job... Commented Mar 15, 2020 at 12:03

3 Answers 3

5

First of all, as @buran commented, there is no need to use str, the following suffices:

new_file_path = os.path.join(dir_path, 'mynewfile.txt')

There is a distinction between where the script exists, given by __file__, and the current working directory (usually the place from which the script was invoked), given by os.getcwd(). It is not entirely clear from the question wording which one was intended, although they are often the same. But not in the following case:

C:\Booboo>python3 test\my_script.py

But they are in the following case:

C:\Booboo>python3 my_script.py

But if you are trying to open a file in the current working directory, why should you even be bothering with making a call to os.getcwd()? Opening a file without specifying any directory should by definition place the file in the current working directory:

import os

with open('mynewfile.txt', "x") as f:
    # do something with file f (it will be closed for you automatically when the block terminates

Another problem may be that you are opening the file with an invalid flag, "x" if the file already exists. Try, "w":

with open(new_file_path, "w") as f:
    # do something with file f (it will be closed for you automatically when the block terminates
Sign up to request clarification or add additional context in comments.

4 Comments

What if you invoke the script from another directory? It's creating the file in the other directory, not where the script is - so that would be one reason.
@Levon To what question is your comment an answer to?
I meant to refer to this. "Opening a file without specifying any directory should by definition place the file in the current working directory:" I'm starting a Python script in my home directory (let's say /home/levon) from some other directory (/root) . The script is creating a log file open('logfile.txt', a), but rather than creating the logfile in /home/levon where the script is located, it creates it in /root.
@Levon I agree with you 100% and nowhere in my post did I say anything contradictory to that (or ask a question). I said, ... and the current working directory (usually the place from which the script was invoked), given by os.getcwd(). I am saying that the current working directory by default (unless you change it) is the directory from which the script is invoked. In your example that would be /root. Am I missing something?
1

have you tried simply

import os

dir_path = os.getcwd()
open(dir_path +'mynewfile.txt', "x")

Edit: Sorry for the last message, it saved incomplete

5 Comments

sorry, that was a sending problem. Please try again with the current code
First, you need dir_path + os.path.sep + 'mynewfile1.txt' or this open can't even succeed. Second, by default if you do not specify a directory, the system will attempt to open the file in the current working directory by default (that is the definition of the current working directory), so that makes using os.getcwd() totally unnecessary. How can this be the accepted answer?
Hello brother. os.getcwd() returns a string containing the current path where the python script was called. using a simple string concatenation, he was able to sucessfully use the function open.(the current path plus the filename). Cheers!
Then he would have to have been in the root directory /. In any other directory, such as /home/Roni, getcwd() would just return /home/Roni without a trailing path separator and your code would not work in the general case (as would blindly adding a path separator would not work if you are in the root directory). That is why you would want to use os.path.join, which will work for both cases. So my comment was based on your answer as *a general solution." My other point is that calling getcwd() is altogether unnecessary. Just open('mynewfile.txt', 'x')..
That is, if you want to open in the current working directory, which can be but not necessarily the same as the directory that holds the script file. And it's not 100% clear from the OP's question (at least not to me), which one he really wants because his attempt is using __file__, which is where the file lives, but he likes your getcwd(), which is the current working directory, and again, they may not always be the same.
0

you need to use os.getcwd to get the crrent working directory

import os

dir_path = os.getcwd()
new_file_path = str(os.path.join(dir_path, 'mynewfile.txt'))
open(new_file_path, "x")

4 Comments

And if you just did open('mynewfile.txt', 'x'), what directory would the file it go into if not the current working directory?
who knows ? :/ -(' ')/-
Answer: The current working directory. In other words, there is no reason for calling os.getcwd() to put a file into the current working directory.
you got A+ for this solution, congrats boohoo

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.