这是我的文件系统的示例结构,我在.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
答案 0 :(得分:1)
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
检查@hansolo的答案,因为这实际上是相同的
如果您有文件夹: /hcdlprd/user/head/some/dir/file.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
答案 1 :(得分:0)
您可以读入这些行,用.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)
答案 2 :(得分:0)
在任何外壳中:
mkdir -p /hcdlprd/user/moka.babu/hive
该命令将创建整个结构。
答案 3 :(得分:0)
尝试一下
$ cat file
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
$ awk '{ system("mkdir -p " $NF); }' file
您可以看到创建的结构。