文件去重
在做數據分析或者運維時候,經常需要使用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 ")
閱讀更多 技術信仰 的文章