从Python中删除文件夹中的文件

huangapple go评论58阅读模式
英文:

Removing files from folders in Python

问题

我正在从许多文件夹中删除特定文件。但是当某个文件在文件夹中不存在时,会出现错误。基本上,我希望代码扫描每个文件夹,查看文件是否存在并删除它。如果特定文件夹中没有文件,它应该跳过,因为没有要删除的内容,并转到下一个文件夹。

错误是:

FileNotFoundError: [WinError 2] The system cannot find the file specified.
英文:

I am removing a certain file from many folders. But when that file is missing in a folder, it runs into an error. Basically, I want the code to scan every folder, see if the file exists there and delete it. If there is no file in a specific folder, it should skip that since there is nothing to delete and move to the next folder.

import os
N = [i+1 for i in range(101)]
I=[]

for i in N:
    if i in I:
        continue
    os.remove(rf"C:\Users\User\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D0 nodes_seed75_var1_1000stepsize_0.4initial_K_1e3\{i}\Indices.txt")

The error is

FileNotFoundError: [WinError 2] The system cannot find the file specified.

答案1

得分: 1

Python有一个名为try/except的指令,允许你执行可能引发异常的操作,如果引发了异常,则捕获此异常并采取相应措施。

有关这些指令的一些文档可以在这里找到。

我只是将它添加到你的代码中,以便你看到一个示例:现在脚本尝试删除文件。如果无法删除文件,因为文件不存在,那么它将引发一个FileNotFoundError异常,该异常将被except块捕获,在那里打印一些内容。

英文:

Python has instructions called try / except allowing you to perform an action that could raise an exception, catch this exception if it is raised, and act consequently.

Some documentation about these instructions can be found here.

I simply added it to your code for you to see an example: the script now tries to remove the file. If it cannot do it because the file does not exist, then it will raise a FileNotFoundError that will be catched by the except block, where it prints something.

import os
import sys
N = [i+1 for i in range(101)]
I=[]

for i in N:
    if i in I:
        continue
    try:
    	os.remove(rf"C:\Users\User\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\220 nodes_seed75_var1_1000stepsize_0.4initial_K_1e3\{i}\Indices.txt")
    except FileNotFoundError:
    	print(f"File does not exist inside of {i} folder.", file=sys.stderr)

huangapple
  • 本文由 发表于 2023年6月22日 15:22:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定