deleting file if it exists; python

前端 未结 5 770

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:53

    Try this:

     from os import path, 
        PATH = os.path.expanduser('~') + '\Desktop\input.txt'
        if path.isfile(PATH):
           try:
              os.remove(os.path.expanduser('~') + '\Desktop\input.txt')
           except OSError:
              pass
    

    edited :

    from os import path, 
            PATH = os.path.expanduser('~') + '\Desktop\input.txt'
            try:
                os.remove(os.path.expanduser('~') + '\Desktop\input.txt')
            except OSError:
                pass
    

提交回复
热议问题