删除文件(如果存在);蟒蛇

时间:2013-04-23 11:19:39

标签: python file-io try-catch

我想创建一个文件;如果它已经存在我想删除它并重新创建它。我尝试这样做,但它抛出Win32错误。我做错了什么?

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

5 个答案:

答案 0 :(得分:25)

您正在尝试删除一个打开的文件,以及os.remove()状态的文档......

  

在Windows上,尝试删除正在使用的文件会导致引发异常

您可以将代码更改为...

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

...或者你可以用......替换所有这些......

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

...在打开之前会将文件截断为零长度。

答案 1 :(得分:3)

您尝试在文件打开时删除该文件,您甚至不需要with删除该文件:

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

删除是否存在

答案 2 :(得分:2)

你可以使用open with mode parameter ='w'。如果省略mode,则默认为'r'。

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

w 将文件截断为零长度或创建用于写入的文本文件。             流位于文件的开头。

答案 3 :(得分:1)

Windows不允许您删除打开的文件(除非使用不寻常的共享选项打开它)。在删除之前你需要关闭它:

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

答案 4 :(得分:1)

试试这个:

 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

编辑:

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