我想删除文件,如下所示:
npm run watch
哪个不行。如果我尝试运行
path = "username/hw/01/"
file_list = ["main.cc", "makefile"]
files = os.listdir(path)
del_files = list(set(files) - set(file_list))
for del_file in del_files:
try:
os.remove(path + del_file)
except FileNotFoundError as e:
print("\t" + e.strerror)
except OSError as e:
print("\t" + e.strerror)
异常触发。但是,如果使用ls或nautilus进行检查后,文件仍然存在。
什么有效
....
try:
os.remove(path + del_file)
os.remove(path + del_file)
except ...
这非常难看。当包含print语句时,它将运行多次以获取所有请求的文件。我错过了什么?
如果重要,
files = os.listdir(path)
del_files = list(set(files) - set(file_list))
while (del_files):
for del_file in del_files:
try:
os.remove(path + del_file)
time.sleep(0.5)
print("\t\tRemoving " + path + del_file)
except FileNotFoundError as e:
print("\t" + e.strerror)
except OSError as e:
print("\t" + e.strerror)
files = os.listdir(path)
del_files = list(set(files) - set(file_list))
答案 0 :(得分:0)
如果路径不以路径分隔符结尾,则可能需要使用os.remove(os.path.join(path, del_file))
而不是os.remove(path + del_file)
。文档:os.path.join()