Python os.mkdir, file exists

Asked

Viewed 273 times

0

I am trying to download videos, but when it goes to the next one, it returns the error saying that the folder already exists. There is no way to save more than one file?

Retorno do erro

def json_decoder(file):
    file = open(file, 'r')
    file = file.read().replace(chr(92) * 2, chr(92))
    file = codecs.decode(file, 'unicode_escape')
    lst = file.split('\n')
    tofile = []
    for i in lst:
        if not i:
            continue
        j = i.index(':') + 2
        k = i.index('"', 50)
        tofile.append(i[j:k])
    try:
        os.remove('output.txt')
    except OSError:
        pass
    with open('output.txt', 'w') as f:
        for item in tofile:
            print(item)
            f.write(f'{item}\n')

def get_files(data):
    file = open(data, 'r')
    lst = file.read().split('\n')
    for i in lst:
        if not i:
            continue
        video_name = i.split('=')[-1]
        print('Downloading ' + video_name)
        r = requests.get(i)
        if os.path.isdir("./" + video_name.split('-')[0]) is not True:
            os.mkdir(video_name[:3])
        with open(video_name[:3] + "/" + video_name, 'wb') as f:
            f.write(r.content)

I’m using python 3.7.1

  • You can save more than one file, which you cannot create an already created folder.

1 answer

5


Try to use the os.makedirs(), it has a parameter exist_ok that when True no error if directory already exists.

os.makedirs(video_name[:3], exist_ok=True)
  • Perfect! That was it, thanks! It was right! Thank you

Browser other questions tagged

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