Python | 删除现有文件(os.remove()方法的示例)
删除现有文件
要删除/删除现有的文件-我们用“remove()法”的操作系统“”模块-所以访问的“remove()法”,我们必须导入模块“OS”。
模块导入语句:importos
remove()方法的语法:os.remove(file_name)
在这里,file_name是现有文件的名称。
示例1(删除现有文件):
import os
def main():
fo = open("data.txt","wt") #创建一个文件
fo.write("Hello") #写内容
fo.close() #关闭档案
#检查文件是否存在?
if os.path.exists("data.txt"):
print("data.txt exists...")
else:
print("data.txt doe not exist...")
#删除文件
os.remove("data.txt")
#检查文件是否存在?
if os.path.exists("data.txt"):
print("data.txt exists...")
else:
print("data.txt doe not exist...")
if __name__=="__main__":main()输出结果
data.txt exists... data.txt doe not exist...
示例2(尝试删除不存在的文件):
import os
def main():
#删除不存在的
os.remove("abc.txt")
if __name__=="__main__":main()输出结果
Traceback (most recent call last)
File "/home/main.py", line 8, in <module>
if __name__=="__main__":main()
File "/home/main.py", line 6, in main
os.remove("abc.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'示例3(处理“FileNotFoundError”异常)
import os
def main():
try:
#删除不存在的
os.remove("abc.txt")
except FileNotFoundError:
print("ERROR:abc.txtdoes not exist...")
except:
print("Unknown error...")
if __name__=="__main__":main()输出结果
ERROR:abc.txtdoes not exist...