dvnt
dvnt

Reputation: 193

Creating a file inside a directory

I'm currently creating a script that has 2 modes: one for creating files, another for creating folders.

What I currently have when it comes to creating files is:

elif mode == "B":
    fileName = input("What's the name of the file you'd like to create? ")
    filePath = input("Where would you like this file to go? ")
    if not os.path.exists(fileName):
        f = open(fileName, "x")
        print("File", fileName, "created")
    else:
        print("File", fileName, "already exists")

As is, it creates the file on the same directory of the .py script. How could I make it create inside the directory specified at filePath = input("Where would you like this file to go? ")(assuming it exists) and throwing an error in case said directory does not currently exist?

Upvotes: 0

Views: 551

Answers (3)

Jackson Horton
Jackson Horton

Reputation: 14

In order, you should check that the file path exists(if not create it), then check if the file exists, then create the file.

# This will check if the filePath doesn't exists, then create it if it doesn't exist:
if not os.path.exists(filepath):
    os.makedirs(filePath)

Next, check if the file exists in the correct path.

filePath = './'
fileName = 'test.py'

# Checks if file exists w/ an else exception, so you fill in what you want to do
if os.path.exists(os.path.join(filePath, fileName)):
    # Do something if the file already exists
    print('file already exists')
else:
    # Create file
    print('file doesn\'t exists')

Upvotes: 0

Ayk Borstelmann
Ayk Borstelmann

Reputation: 316

Before the if not os.path.exists(...) you could check if filePath exists and if not create it with os.mkdir(filePath)

Upvotes: 1

AKX
AKX

Reputation: 169378

Use os.path.join():

final_file_name = os.path.join(filePath, fileName)

The path must exist, or you can create it beforehand with

os.makedirs(filePath, exist_ok=True)

Upvotes: 1

Related Questions