首页 > 解决方案 > 如何在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

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

标签: python

解决方案


我会推荐以下方法:

import os
from pathlib import Path

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

这适用于跨平台,并且不会覆盖已经存在的目录。


推荐阅读