在Python中删除文件夹中的所有文件
我正在尝试用Python编写一个程序,该程序将删除在Python中删除文件夹中的所有文件,python,python-3.x,temporary-files,temp,Python,Python 3.x,Temporary Files,Temp,我正在尝试用Python编写一个程序,该程序将删除%temp%路径中的所有文件,也称为C:\Users\User\AppData\Local\temp 我该怎么做?我使用的是Python 3.4。通常,您可以使用删除文件夹中的所有文件/目录: #!/usr/bin/env python import shutil import tempfile dirpath = tempfile.mkdtemp() try: # use the temporary directory here
%temp%
路径中的所有文件,也称为C:\Users\User\AppData\Local\temp
我该怎么做?我使用的是Python 3.4。通常,您可以使用删除文件夹中的所有文件/目录:
#!/usr/bin/env python
import shutil
import tempfile
dirpath = tempfile.mkdtemp()
try:
# use the temporary directory here
...
finally:
shutil.rmtree(dirpath) # clean up
如果您只需要上面的内容(从头创建一个临时目录),则可以编写得更简单:
注意:在POSIX上,临时目录可能设置了一个粘滞位:即,您可能没有删除临时目录中所有文件的权限。我不认为这个问题是重复的,因为OP询问的是临时文件夹删除。链接的答案不引用临时文件夹。对于临时文件,您可以使用tempfile模块。可能重复的
#!/usr/bin/env python3
import tempfile
with tempfile.TemporaryDirectory() as dir:
print(dir.name) # use the temporary directory here