在目录中创建文件

Creating a file inside a directory

我目前正在创建一个具有 2 种模式的脚本:一种用于创建文件,另一种用于创建文件夹。

我目前在创建文件时拥有的是:

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

照原样,它会在 .py 脚本的同一目录中创建文件。我如何让它在 filePath = input("Where would you like this file to go? ") 指定的目录中创建(假设它存在)并在该目录当前不存在的情况下抛出错误?

使用os.path.join():

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

路径必须存在,或者您可以预先创建它

os.makedirs(filePath, exist_ok=True)

if not os.path.exists(...) 之前,您可以检查 filePath 是否存在,如果不存在,则使用 os.mkdir(filePath)

创建它

依次检查文件路径是否存在(如果不创建),再检查文件是否存在,再创建文件。

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

接下来,检查文件是否存在于正确的路径中。

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