如何在Python中从文本文件创建文件夹

时间:2018-07-23 09:46:51

标签: python file parsing directory

我是Python的新手,正在尝试根据文本文件在层次结构中创建文件夹。

例如,文本如下:

{!! Form::open(array('route' =>   
            'category.store','method'=>'POST','files'=>true)) !!}

    @if(count($errors))
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br/>
        <ul>
            @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
  @endif

  <div class="row">
    <div class="col-md-6">
     <div class="form-group">     
{{ Form::label('Car Type', 'Car Type') }}
{{ Form::text('cartype', null, array('class' => 'form-control')) }}
<span class="text-danger">{{ $errors->first('cartype') }}</span>
    </div>
  </div>
 </div>

需要如下创建文件夹:

ant:ant:jar:1.5.1

com.fasterxml.jackson.core:jackson-annotations:jar:2.8.10

com.fasterxml.jackson.core:jackson-core:jar:2.7.3

com.fasterxml.jackson.core:jackson-core:jar:2.8.10

要解析的部分代码:(off.txt)

ant\ant\1.5.1

com\fasterxml\jackson\core\jackson-annotations\2.8.0

com\fasterxml\jackson\core\jackson-core\2.7.3

com\fasterxml\jackson\core\jackson-core\2.8.10

编写文件夹的部分代码:

with open('off.txt') as f:

content = f.readlines()

for dependency in content:

slicedDependency = dependency.split(':')

var0 = slicedDependency[0]

if not var0.__contains__('.'):
    var1 = slicedDependency[1]
    var2 = slicedDependency[2]
    var4 = slicedDependency[3]

else:
    folderHirearchy = var0.split('.')

    if var0.__contains__('.'):

        for folder in folderHirearchy:
            print(folder)

1 个答案:

答案 0 :(得分:0)

正则表达式在此类情况下发挥了作用

import re
import os

expr = re.compile(r"(?<!\d)[.:](?!\d+)")
with open("./off.txt", "r") as f:
  lines = f.readlines()
  """use a list comprehension and re.sub to replace dots and colons with slashes ("/"),
  and the "jar:"
  """
  folders = [
    expr.sub("/", line).replace("jar:","") for line in lines
    if len(line) > 1
  ]

for f in folders:
  print f
  os.makedirs(f)