3

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

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

What I did is this.

import os
os.rename('A.txt','Btxt')

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

user42459
  • 883
  • 3
  • 12
  • 29

1 Answers1

2

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

In case A.txt does not exists it checks that B.txt does.

import os

if os.path.isfile("A.txt"):
    if not os.path.isfile("B.txt"):
        os.rename('A.txt','B.txt')
else:
    assert os.path.isfile("B.txt") , "Neither A.txt or B.txt exists"
igon
  • 3,016
  • 1
  • 22
  • 37