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)
这适用于跨平台,并且不会覆盖已经存在的目录。
推荐阅读
- php - 音频跟踪/分析/统计
- hexo - Hexo 内部链接到页面部分
- jmeter - 线程组中各项的处理顺序是怎样的?
- c++ - 关于 C++ 中的 Lambda 函数
- php - php pdo查询while循环有问题
- vue.js - 如果数据属性在 VueJs 中从父组件传递到子组件,则无法将其作为对象进行操作
- flutter - Flutter 中的弯曲文本
- css - 如何使用 Spring Boot 将 CSS 文件链接到 JSP?
- wordpress - 在 WordPress 自定义端点上获取 slug
- android - 尝试在 Android 中的 Fragmet 创建一个 PiChart,但期望没有找到该类