如果存在则删除文件;蟒蛇 [英] deleting file if it exists; python

查看:153
本文介绍了如果存在则删除文件;蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个文件;如果它已经存在,我想删除它并重新创建它。我尝试这样做,但它会引发Win32错误。

 尝试:
with open(os.path.expanduser('〜')+ '\Desktop\input.txt'):
os.remove(os.path.expanduser('〜')+'\Desktop\input.txt')
f1 = open(除了IOError:
f1 = open(os.path.expanduser('〜')+'\Desktop\input.txt','a')
)+'\Desktop\input.txt','a')


解决方案

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


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

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


$ b $

  filename = os.path.expanduser('〜')+'\Desktop\input.txt'
try:
os.remove(filena我)
除了OSError:
传递
f1 = open(文件名,'a')

...或者你可以用...替换所有的...

$ $ p $ f1 = open(os。 path.expanduser('〜')+'\Desktop\input.txt','w')

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


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?

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')

解决方案

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.

这篇关于如果存在则删除文件;蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆