简体   繁体   English

如何在python中创建文件夹?

[英]How to create a folder in python?

I am running a code in python where I get images from input file, and create another folder as output and a file csv.我在 python 中运行一个代码,我从输入文件中获取图像,并创建另一个文件夹作为输出和一个文件 csv。 The code that I run is as below:我运行的代码如下:

# 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()

After running the code I get only csv file, but I don't get output folder.运行代码后,我只得到 csv 文件,但我没有得到输出文件夹。 The way I run the code is:我运行代码的方式是:

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

Please can you help me how to solve the problem, because I need the output folder for next steps, running next functions.请你能帮我解决这个问题吗,因为我需要输出文件夹用于下一步,运行下一个功能。

I would recommend the following approach:我会推荐以下方法:

import os
from pathlib import Path

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

This works cross-platform and doesn't overwrite the directories if they already exist.这可以跨平台工作,并且如果目录已经存在,则不会覆盖它们。

While most answers suggest using os.mkdir() I suggest you rather go for os.makedirs() which would recursively create all the missing folders in your path, which usually is more convinient.虽然大多数答案都建议使用os.mkdir()我建议您选择os.makedirs() ,它会递归地创建路径中所有丢失的文件夹,这通常更方便。

import os
os.makedirs('foo/bar')

Docs: https://docs.python.org/3/library/os.html#os.makedirs文档: https : //docs.python.org/3/library/os.html#os.makedirs

You should try the os module.您应该尝试os模块。 It has a mkdir method that creates a directory based on the path you give it as a parameter.它有一个mkdir方法,可以根据您作为参数提供的路径创建一个目录。

import os
os.mkdir("path")

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

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