简体   繁体   English

删除第n个文件Python

[英]Delete every n-th file Python

I'm looking to delete every 10th file from a folder using a Python script. 我正在寻找使用Python脚本从文件夹中删除第10个文件。 I looked around and found this code: 我环顾四周,发现以下代码:

import os
l = os.listdir('/Users/myname/Desktop/TBD')

for n in l[::10]:
    os.unlink(n)

I created a Python script for this then ran it in terminal using 我为此创建了一个Python脚本,然后在终端中使用

python filename.py

And this is what I get in return: 这就是我得到的回报:

FileNotFoundError: [Errno 2] No such file or directory: 'Pic-1.jpg'

The folder I point to with the code is the folder containing 1000 photos. 我用代码指向的文件夹是包含1000张照片的文件夹。 It's reading the name of the first folder but isn't going through with the delete process. 它正在读取第一个文件夹的名称,但并未执行删除过程。 Is there a better way of doing this? 有更好的方法吗?

It's because listdir() is returning you just names of entries in specified folder, without path element. 这是因为listdir()仅返回指定文件夹中条目的名称,而不包含path元素。 So when you try to unlink these files, you try to do that in context of current working directory, not in /Users/myname/Desktop/TBD/ as you should. 因此,当您尝试取消链接这些文件时,请尝试在当前工作目录的上下文中执行此操作,而不是在/Users/myname/Desktop/TBD/中执行此操作。 Simply add path to each filename you want to unlink or ensure /Users/myname/Desktop/TBD is your working directory. 只需为要取消链接的每个文件名添加路径,或确保/Users/myname/Desktop/TBD是您的工作目录。

Additionally, for general safety you should check if element you are about to unlink is in fact a file, not ie directory or anything else: 另外,为了安全起见,您应该检查要取消链接的元素是否实际上是文件,而不是目录或其他任何文件:

import os

dir_to_clean = '/Users/myname/Desktop/TBD'
l = os.listdir(dir_to_clean)

for n in l[::10]:
    target = dir_to_clean + '/' + n
    if os.path.isfile(target):
        os.unlink(target)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM