python - 如何在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)

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

关于python - 如何在python中创建文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60478921/

相关文章:

python - 使用均值合并 Pandas 中的数据帧

python - 将一个字典的元素与另一字典中的值范围进行比较

python - 如何将 subprocess.call() 输出推送到终端和文件?

python - 用 Cython 包装包含 wxString 的 C++ 类

python - MQTT (Mosquitto) over TLS - 某些程序中的证书错误

python - 无法使用 jinja2 将 float 舍入为整数

python - 在 TensorFlow 中展平数据集

python - signal.spectrogram 返回太多赫兹

python - 使用scrapy,如何获取部分xpath解析结果?

python - 在另一个装饰器之前使用 PyQt 4's ' pyqtSlot' 装饰器的奇怪行为