如何使用python或shell创建下面的文件夹结构?

2024-09-30 01:21:55 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

这是我的文件系统的示例结构,我在.text文件中有文件夹名,我在Shell脚本或python中调用这个文件如何递归地创建这个文件结构,我只需要下面结构中的文件夹名?你知道吗

d-r-x   - moka.babu HDFS   0 2018-08-23 12:58 /HCDLPRD/user
d-r-x   - moka.babu HDFS   0 2018-08-23 12:58 /hcdlprd/user/moka.babu
d-r-x  -  moka.babu HDFS   0 2018-08-23 12:58 /hcdlprd/user/moka.babu/hive

Tags: 文件text脚本文件夹示例hdfsshell结构
3条回答

使用Python

OP声明ls -ltr被显式复制到一个文件中。我们可以先用awk清理它,只将文件放入文件中

awk -F '[[:space:]]+' 'NR > 1 {print $9}' file >> cleaned.txt

这将把每一行按多个空格分成几部分,并将文件名(在第9列中)发送到该文件,产生以下结果:

/ranger/audit/atlas/20180629
/ranger/audit/atlas/20180630

在python中:

import os
# open the file to be read
with open('cleaned.txt') as fh:

    for dir in fh:
        try:
            os.mkdir(dir)
            # If you don't want root write access
            os.chmod(dir, 555)
        # In case the root directory already exists
        except FileExistsError as e:
            print(e)
            continue

在bash中

检查@hansolo的答案,因为这实际上是相同的

编辑:以防目录中的一个文件夹可能不存在

如果您有文件夹: /hcdlprd/user/head/some/dir/文件.txt你知道吗

如果head不是由脚本这一行之前创建的,您可以创建一个更健壮的解决方案:

try:
    os.mkdir(dir)
except FileExistsError as e:
    print(e)
except FileNotFoundError as e:
    sub_dir, i = "", 1

    # filenotfound will show that some component of the path doesn't exist
    # so we will check the sub-directories for existence and
    # make them if they are empty
    while sub_dir!=dir:
        # grab a sub-directory ('/path/to/subdir')
        sub_dir = os.path.join(os.path.split(dir)[:i])
        # check if it's not a directory, if not make it
        # if it is, continue on
        if not os.path.isdir(sub_dir):
            os.mkdir(sub_dir)
        i+=1

如果awk的概念化有点奇怪,我们可以用python包装所有内容,方法是用以下代码处理每一行:

def process_lines(fh):
    for line in fh:
        split_out = line.split() # split on spaces, creating a list
        path = split_out[-1] # the file is the last entry
        yield path

with open('cleaned.txt') as fh:
    for dir in process_lines(fh):
        # rest of code at top

您可以读取中的行,用.split(' ')分割空间中的每一行,然后索引最后一个值以获得文件夹名称。然后就是import os后跟for folder in folders:os.mkdir(folder)

下面是一个带有基本错误检查的示例,它将打印无法创建的文件:

import os

with open('files.txt', 'r') as file:
    file_list = file.readlines()

for file in file_list:
    filename = file.split(' ')[-1].rstrip()[1:]
    try:
        os.mkdir(filename)
    except Exception as e:
        print(e)

在任何壳中:

mkdir -p /hcdlprd/user/moka.babu/hive

该命令将创建整个结构。你知道吗

相关问题 更多 >

    热门问题