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 os
def 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 os

def 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 '\\n' > {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 ")
Python使用技巧:调用shell命令对文件进行去重和清除空白行


分享到:


相關文章: