deleting file if it exists; python

前端 未结 5 758

I want to create a file; if it already exists I want to delete it and create it anew. I tried doing it like this but it throws a Win32 error. What am I doing wrong?

5条回答
  •  再見小時候
    2020-12-30 05:33

    Windows won't let you delete an open file (unless it's opened with unusual sharing options). You'll need to close it before deleting it:

    try:
        with open(os.path.expanduser('~') + '\Desktop\input.txt') as existing_file:
            existing_file.close()
            os.remove(os.path.expanduser('~') + '\Desktop\input.txt')
    

提交回复
热议问题