0

**I'm trying to delete a file in python but it keeps displaying this error when use os.remove() in an elif statement: The process cannot access the file because it is being used by another process: 'filename.txt'

#1
import os
fileName = open("filename.txt", "r")

#print(fileName.name)

fileName.close()
userFileName = input("Please enter your file name: ")
newFileName = open(str(userFileName+".txt"), "a")


#print(newFileName.name)
#2

if newFileName.name != fileName.name:
    FileWrite = input("Please enter the text you want to write to the file: ")
    newFileName.write(FileWrite)
    newFileName.close()
    #os.remove("filename.txt")  {This works}
else: 
     #{Not working}
    appendFile = input("Do you want to Read, Delete or Append file: ")
    if appendFile == "Read":
        fileName = open("filename.txt", "r")
        file_contents = fileName.read()
        print(file_contents)

    elif appendFile == "Delete":
        fileName.close()
        os.remove("filename.txt")
ShivaGuntuku
  • 5,274
  • 6
  • 25
  • 37
Hello123
  • 1
  • 1

0 Answers0