python - 如何在python中创建文件夹?

我在 python 中运行一段代码,从输入文件中获取图像,并创建另一个文件夹作为输出和一个文件 csv。我运行的代码如下:

# import the necessary packages
from PIL import Image
import argparse
import random
import shutil
import glob2
import uuid

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required = True,
    help = "input directory of images")
ap.add_argument("-o", "--output", required = True,
    help = "output directory")
ap.add_argument("-c", "--csv", required = True,
    help = "path to CSV file for image counts")
args = vars(ap.parse_args())

# open the output file for writing
output = open(args["csv"], "w")

# loop over the input images
for imagePath in glob2.iglob(args["input"] + "/*/*.jpg"):
    # generate a random filename for the image and copy it to
    # the output location
    filename = str(uuid.uuid4()) + ".jpg"
    shutil.copy(imagePath, args["output"] + "/" + filename)

    # there is a 1 in 500 chance that multiple copies of this
    # image will be used
    if random.randint(0, 500) == 0:
        # initialize the number of times the image is being
        # duplicated and write it to the output CSV file
        numTimes = random.randint(1, 8)
        output.write("%s,%d\n" % (filename, numTimes))

        # loop over a random number of times for this image to
        # be duplicated
        for i in range(0, numTimes):
            image = Image.open(imagePath)

            # randomly resize the image, perserving aspect ratio
            factor = random.uniform(0.95, 1.05)
            width = int(image.size[0] * factor)
            ratio = width / float(image.size[0])
            height = int(image.size[1] * ratio)
            image = image.resize((width, height), Image.ANTIALIAS)

            # generate a random filename for the image and copy
            # it to the output directory
            adjFilename = str(uuid.uuid4()) + ".jpg"
            shutil.copy(imagePath, args["output"] + "/" + adjFilename)

# close the output file
output.close()

运行代码后,我只得到 csv 文件,但没有得到输出文件夹。 我运行代码的方式是:

python gather.py --input 101_ObjectCategories --output images --csv output.csv

请你帮我解决这个问题,因为我需要输出文件夹用于下一步,运行下一个功能。

最佳答案

我推荐以下方法:

import os
from pathlib import Path

Path('path').mkdir(parents=True, exist_ok=True)

这适用于跨平台并且不会覆盖目录(如果它们已经存在)。

https://stackoverflow.com/questions/60478921/

相关文章:

c++ - 如何解决 C++ std::string_view 超出范围的问题?

c++ - 如何正确删除C++中的指针?

amazon-web-services - 使用 axios 和 aws4 向 aws 进行身份验证

c# - 获取错误 System.IO.IOException : 'The process can

python - 在python中将类返回给自身

three.js - 如何使用 threejs 在 iPhone 上启用视网膜分辨率 render.

python - 按升序对月份名称字符串列表进行排序

javascript - 显示到小数点后两位 - React.Js

swiftui - 使用 SwiftUI 实现 PencilKit 撤消功能

javascript - 运算符 '<' 不能应用于类型 'Date' 和 'number' .ts