Creating directories in Python

Asked

Viewed 526 times

1

I have a list of directories to be created that has this structure :

Bla / Bla / Bla1.md

Bla / Bla / Bla2.md

Blu / Blue.md

Ble.md

But the archives .md should not be created, but the folders containing the same should, and for that I made the following script :

# -*- coding: utf-8 -*-

import os


def build ( address ) :

    address = '/home/bezerk/Imagens/' + address

    if not os.path.exists ( address ) :

        os.makedirs ( address )


with open ( 'Arquivo.txt', 'r' ) as file :

    for line in file.readlines () :

        if line.endswith ( '.md' ) :

            # Tratamento aqui

            build ( line [:-3] )

        else :

            build ( line )

But I don’t know why python doesn’t recognize this Bla / Bla / Bla1.md but a separate item like this one Ble.md he recognizes, if anyone can give me insights to solve I am grateful

  • 1

    What do you mean by "python doesn’t recognize"? I made a test here by making the directories with the names you suggest and worked normally.

  • When I run here on my pc it doesn’t create folders like Bla / Bla / Bla1.md that has more than one directory inside, but if I put in the file txt only folders without subfolders it creates them perfectly ( This is what I was wondering because I didn’t see anything wrong in the code, but ... ) - and when it creates, folders are created with extension .md and becomes a mess

1 answer

0


Try to do the tests below and if you get the same results, the error is in your file processing logic, if the results are different there is something rotten in the realm of :-) go to the command line:

$ cd ~
~$ python

from os import makedirs as mkdir
d1 = 'teste1/bla/bla/bla.md'
mkdir(d1)

Quit Pyton and run the command tree to see the tree created from teste1.

tree teste1  

Arvore criada pel makedirs

Go back to python and do:

d2 = 'test2 / bla /bla /bla.md'
mkdir(d2)

Quit python and try running the command tree to get the tree from the directory teste2 and you will get an error:

$ tree teste2
teste2 [error opening dir]

Why does this happen? for the reason that, in fact, there is no directory called "teste2" but "teste2 " (with a space after 2), then command tree shall be executed as follows:

$ tree teste2\ 

Note that after the bar there is a space, this command results in the figure below:

Arvore gerada pelo makedirs com "teste2 "

I ran the tests on a Ubuntu 16, maybe your problem is in the spaces between the bars, unless this is mandatory, try to remove them, spaces in directory names can be a source of problems, if you have to keep them remember that you will have to use scape for reference-los.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.