Home > Enterprise >  Make a program delete a file which it just created
Make a program delete a file which it just created

Time:12-01

Is there a way for me to stop an action in python so that another action in the same python script can start? Or is there a way to split a program into two parts so that they can run after the first part has ended?

    import os

    t = 'Testfile input...'

    f = open('File.txt', 'w')
    f.write('{}'.format(t))

    os.remove('File.txt')
    print('File has been removed')

This is what I always get.

    PermissionError: [WinError 32] The process cannot access the file because it is 
    being used by another process: 'File.txt'

CodePudding user response:

You need to close the file before you can remove it with f.close()

import os

t = 'Testfile input...'

f = open('File.txt', 'w')
f.write('{}'.format(t))
f.close()
os.remove('File.txt')
print('File has been removed')

Otherwise your file system will not allow you to delete it because it still in use.

  • Related