python list去重_Python使用技巧:调用shell命令对文件进行去重和清除空白行

文件去重

在做数据分析或者运维时候,经常需要使用python给文件去重,往往处理的方式是将文件读入一个结合或者使用循环去重。这种方式本质上将文件读入内存,面对大文件时候,就很难操作。

其实,python是可以调用shell命令。下面这行命令就是使用shell给file_1.txt文件去重得到file_2.txt:

cat file_1.txt|awk '!a[$0]++'>file_2.txt

python 调用shell命令的方式为:

os.system(shell_command)

结合以上两点可以封装一个python函数给文件去重:

import osdef unique_file(path): file_dir_list = path.split("/") del file_dir_list[-1] file_dir_list.append("tmp_file.txt") tmp_path = "/".join(file_dir_list) command = "cat {0}|awk '!a[$0]++'>{1}".format(path, tmp_path) # command = "cat {0}|sort -u|uniq >{1}".format(path, tmp_path) os.system(command) os.remove(path) os.rename(tmp_path, path) print("Duplicate removal !")

仅需想函数unique_flie传入需要去重的文件路径即可,去重后文件任然保存原文件名。

清除文件的空白行

一个大文件,中可能夹杂空白行,同样可以结合shell命令去掉空白行。

import osdef delete_blank_lines(path): file_dir_list = path.split("/") del file_dir_list[-1] file_dir_list.append("tmp_file.txt") tmp_path = "/".join(file_dir_list) command = "cat {0}|tr -s '' > {1}".format(path, tmp_path) # command = "cat {0}|sort -u|uniq >{1}".format(path, tmp_path) os.system(command) os.remove(path) os.rename(tmp_path, path) print("delete blank lines ")
351a4ec8ab6841c6b39ae081f6aa1c3b
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值