Clever python program that renames filenames

So I was making a python program that renames A.txt to B.txt, but I wanted the program to skip and move if there is already a B.txt file in the folder. Meanwhile, if there is neither A nor B in the folder, then there is something wrong, so I want the program to show me an error and stop.

So I wanted "if A exists then rename it, if neither A nor B exists then show me an error and stop the program, if only B exists, go to the next line"

I did it.

import os


But if there is no A.txt, the program stops and shows me an error message. How can I encode what I want?


source to share

1 answer

This will only rename A.txt if it exists and B.txt does not.

In case A.txt doesn't exist, it checks what B.txt is doing.

import os

if os.path.isfile("A.txt"):
    if not os.path.isfile("B.txt"):
    assert os.path.isfile("B.txt") , "Neither A.txt or B.txt exists"




All Articles