deleting file if it exists; python

前端 未结 5 759

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')
    
    0 讨论(0)
  • 2020-12-30 05:40

    You're trying to delete an open file, and the docs for os.remove() state...

    On Windows, attempting to remove a file that is in use causes an exception to be raised

    You could change the code to...

    filename = os.path.expanduser('~') + '\Desktop\input.txt'
    try:
        os.remove(filename)
    except OSError:
        pass
    f1 = open(filename, 'a')
    

    ...or you can replace all that with...

    f1 = open(os.path.expanduser('~') + '\Desktop\input.txt', 'w')
    

    ...which will truncate the file to zero length before opening.

    0 讨论(0)
  • 2020-12-30 05:52

    You are trying to remove the file while it is open, you don't even need that with there to delete it:

    path = os.path.join(os.path.expanduser('~'), 'Desktop/input.txt')
    with open(path, 'w'): as f:
        # do stuff
    

    Deletes if it exists

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-30 05:55

    You can use open with mode parameter = 'w'. If mode is omitted, it defaults to 'r'.

    with open(os.path.expanduser('~') + '\Desktop\input.txt', 'w')
    

    w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

    0 讨论(0)
提交回复
热议问题