P
P
pcdesign2015-12-20 21:34:05
Python
pcdesign, 2015-12-20 21:34:05

How to add an underscore to a filename until it turns out that the file does not exist?

There are files:
/tmp/1.txt
/tmp/1_.txt
/tmp/1__.txt
The function accepts a file name. Checks if it exists.
If the file exists, it adds _ and checks again.
And so on until he finds a free option.
That is, in this case, the function should return /tmp/1___.txt
How to implement this in Python?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kazmiruk, 2015-12-20
@pcdesign

import os

fn = "1.txt"

while os.path.exists(fn):
    fn = fn.split('.')
    fn = "".join(fn[:-1]) + "_."  + fn[-1]

M
Max, 2015-12-20
@zenwalker

More or less like this

import os


def safe_path(path):
    name, ext = os.path.splitext(path)

    while True:
        current_name = name + ext
        if not os.path.exists(current_name):
            return current_name
        name += '_'


if __name__ == '__main__':
    open('/tmp/1.txt', 'a').close()
    open('/tmp/1_.txt', 'a').close()
    assert safe_path('/tmp/1.txt') == '/tmp/1__.txt'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question