blahahaaahahaa
blahahaaahahaa

Reputation: 255

How to create a file in the directory where the .py script is ran?

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") 

Upvotes: 3

Views: 2957

Answers (3)

Booboo
Booboo

Reputation: 44128

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

Upvotes: 5

Roni Antonio
Roni Antonio

Reputation: 1460

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

Upvotes: 1

sahasrara62
sahasrara62

Reputation: 11228

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")

Upvotes: 0

Related Questions