简体   繁体   中英

Create path and filename from string in Python

Given the following strings:

dir/dir2/dir3/dir3/file.txt
dir/dir2/dir3/file.txt
example/directory/path/file.txt

I am looking to create the correct directories and blank files within those directories.

I imported the os module and I saw that there is a mkdir function, but I am not sure what to do to create the whole path and blank files. Any help would be appreciated. Thank you.

Here is the answer on all your questions (directory creation and blank file creation)

import os

fileList = ["dir/dir2/dir3/dir3/file.txt",
    "dir/dir2/dir3/file.txt",
    "example/directory/path/file.txt"]

for file in fileList:
    dir = os.path.dirname(file)
    # create directory if it does not exist
    if not os.path.exists(dir):
        os.makedirs(dir)
    # Create blank file if it does not exist
    with open(file, "w"):
        pass

First of all, given that try to create directory under a directory that doesn't exist, os.mkdir will raise an error. As such, you need to walk through the paths and check whether each of the subdirectories has or has not been created (and use mkdir as required). Alternative, you can use os.makedirs to handle this iteration for you.

A full path can be split into directory name and filename with os.path.split .

Example:

import os
(dirname, filename) = os.path.split('dir/dir2/dir3/dir3/file.txt')
os.makedirs(dirname)

Given we have a set of dirs we want to create, simply use a for loop to iterate through them. Schematically:

dirlist = ['dir1...', 'dir2...', 'dir3...']
for dir in dirlist:
   os.makedirs( ... )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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