Python OS – check if file exists, if so rename, check again, then save

Question:

I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filename exists. If it does exist, renames the file in a loop and then saves the file.

What I have currently:

file = request.files['xx']
extension = os.path.splitext(file.filename)[1]
xx = str(uuid.uuid4()) + extension
## if xx exists .. xx = str(uuid.uuid4()) + extension.. loop endlessly.
file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)
Asked By: user7731688

||

Answers:

Have you tried to use the glob Module, it provides an interface similar to ls, you can use it as it follows:

import os
import glob
file_list = glob.glob('my_file')
if len(file_list) > 0:
   os.rename('my_file', 'new_name')

Haven’t tested this yet but you can use os.path.isfile() to check if a file already exists (for directories, use os.path.exists).

import os

def save():
    file = request.files['xx']
    extension = os.path.splitext(file.filename)[1]

    xx = generate_filename(extension)

    file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx))

def generate_filename(extension):
    xx = str(uuid.uuid4()) + extension
    if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], xx)):
        return generate_filename(extension)
    return xx
Answered By: jyap
if not os.path.isfile(xx):
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)
else:
    print("File does not exist")
Answered By: repzero

quick and dirty, haven’t tested this. using the check and rename function recursively to add “_1”, “_2” etc to the end of the file name until it can be saved.

def check_and_rename(file, add=0):
    original_file = file
    if add != 0:
        split = file.split(".")
        part_1 = split[0] + "_" + str(add)
        file = ".".join([part1, split[1]])
    if not os.path.isfile(file):
        # save here
    else:
        check_and_rename(original_file, add+=1)
Answered By: N. Walter

This will check if a file exist and generate a new name that does not exist by increasing a number:

from os import path

def check_file(filePath):
    if path.exists(filePath):
        numb = 1
        while True:
            newPath = "{0}_{2}{1}".format(*path.splitext(filePath) + (numb,))
            if path.exists(newPath):
                numb += 1
            else:
                return newPath
    return filePath
Answered By: Ariel Montes

Improving on N.Walters answer, but so you have a function that just parses the file_path and gives you a valid one back and using the internal Path class:

import os
from pathlib import Path

def check_and_rename(file_path: Path, add: int = 0) -> Path:
    original_file_path = file_path
    if add != 0:
        file_path = file_path.with_stem(file_path.stem + "_" + str(add))
    if not os.path.isfile(file_path):
        return file_path
    else:
        return check_and_rename(original_file_path, add + 1)
Answered By: Dodo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.