繁体   English   中英

在目录中创建文件

[英]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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM