简体   繁体   中英

A loop to increment a number if the file already exists in python

Here is my code trying to achieve this:

    try:
        os.mkdir(f'{path}')
        with open(path + '\\SUSPENDED.txt', 'w') as file:
            file.write('\n'.join(LIST))
    except FileExistsError:
        while FileExistsError:
            i += 1
            os.mkdir(f'{path}_{i}')
            with open(path + '\\SUSPENDED.txt', 'w') as file:
                file.write('\n'.join(LIST))
            break

What Im expecting is if 'path' exists make it 'path_1' and if 'path_1' exists make it 'path_2' and if 'path_2' make it 'path_3' and so on...

Sorry if my question is unclear

All explanations written in code after #:)

import os

target_path = os.path.abspath(os.path.dirname(__file__))  # Path where folder should be created.
base = 'tests'  # Base name of the folder.
i = 0

while True:
    try:
        os.mkdir(base)  # Try creating folder with base name.
    except FileExistsError:
        i += 1  # If folder exists increment an index.
        base = base.split('_')[0] + f'_{i}'  # Split the name by '_' and add index value.
    else:
        with open(os.path.join(target_path, base, 'SUSPENDED.txt'), 'w') as file:  # Create file.
            file.write('FOO')  # Change content for anything you want.
        break  # Task completed, break the while loop :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM