0

I am trying to create a new folder at the location where the python script is saved and then create a new file inside that folder and write information to it. What would be the best way to create the folder and then the path for the file? Thanks a lot.

I used the following code to create the folder

import os
from os import path

nameofFolder = "TestFolder"
foldercheck = os.path.isdir(nameofFolder)
if foldercheck:
    print('Folder present')
else:
    os.makedirs(nameofFolder)

I tried using

completepath = os.path.join(nameofFolder +"/", fileName)

to create a path for the file but that keeps creating the file in the root directory.

Aditya
  • 3
  • 2
  • 1
    Try printing os.getcwd() inside the program. That will tell you what the current working directory is. Make sure it is what you expect. – ProfDFrancis Mar 09 '23 at 08:27
  • See this answer: https://stackoverflow.com/a/3430395/828193. Use `import pathlib; pathlib.Path(__file__).parent.resolve()` to get the directory where the python file is stored at. – user000001 Mar 09 '23 at 08:32

1 Answers1

0

To create the folder:

import os

currentPath = os.getcwd()
nameofFolder = "TestFolder"

if not os.path.exists(currentPath + '/' + nameofFolder):
    os.makedirs(nameofFolder)

To create a file inside of it:

fileName = "Hello"

f = open(nameofFolder + "/" + fileName, "w")

# writing whatever you want:
f.write(...)

f.close()

Or more conveniently:

with open(nameofFolder + "/" + fileName, "w") as f:
   f.write(...)

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34