python-3.x - 使用命令 "ls -t | tail -n +4 | xargs rm --"删除另一个位置的文件

标签 python-3.x linux python-2.7 unix raspberry-pi3

我有一个 RaspBerry Pi 项目,其中 A/D 转换器将 5 分钟长的数据文件收集到数据文件夹中,并且除最新数据外的所有数据将通过 dataFlush.py 脚本和 crontab 每小时删除一次。 dataFlush.py的路径是“/home/pi”,数据文件夹的路径是“/home/pi/dataLog”。那么如何将 dataLog 路径添加到此命令中:

os.system('ls -t | tail -n +2 | xargs rm --')

我尝试了类似的方法,但没有成功:

os.system('ls /home/pi/dataLog -t | tail -n +2 | xargs rm --')

最佳答案

ls(1) 在您的情况下不会生成完整路径输出,因此您可能需要在每一行前面加上“前缀”:

os.system('ls /home/pi/dataLog -t | tail -n +2 | sed 's|^|/home/pi/dataLog/|' | xargs rm --')

另一个选项是使用find(1):

os.system('find /home/pi/dataLog | xargs ls -t -- | tail -n +2 | xargs rm --')

关于python-3.x - 使用命令 "ls -t | tail -n +4 | xargs rm --"删除另一个位置的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58891319/

相关文章:

linux - 如何为一些行运行 awk。?

Python 2.X 在字符串周围添加单引号

python - Pandas:将日期划分为 30 分钟间隔并计算平均值

python - 将多个 CSV 文件合并为一个文件

c++ - linux 指针、引用和方法

windows - 如何将 Linux wxWidgets 应用程序移植到 Windows + Mac

python - 错误pyodbc用python连接sql server

python - 如何在 Python 中将变量打印到文本文件?

python - 仅乘以 Python 字符串中的数值

python - 类型错误 : can only concatenate str (not "set") to str