python对txt⽂件的读写、覆盖写、追加内容、内容按列排序、
内容去重
<⽂件的读
读⽂件demo:
with open('', 'r') as f:
for line in f:
# 遍历f中的每⼀⾏,开始对line进⾏操作
将⽂件读⼊数组中(⽂件中存放的得是数字)
import numpy as np
data = np.loadtxt("")  #将⽂件中数据加载到data数组⾥
<⽂件的写
写⽂件demo:这个也可以是覆盖写⽂件的格式,参数⽤w
with open('', 'w') as writers: # 打开⽂件
a = 'xxx'
writers.write(a) # 将内容写到⽂件中
writers.close() # 关闭⽂件,此处可以理解为保存
在⼀个⽂件尾部追加新内容demo:
with open('', 'a+') as writers: # 打开⽂件
a = 'xxx'
b = 'yyy'
writers.write(a + ‘,’ + b) # 将内容追加到到⽂件尾部
#如果要按⾏写⼊,我们只需要再字符串开头或结尾添加换⾏符'\n'
writers.write(a + '\n')
# 如果想要将多个变量同时写⼊⼀⾏中,可以使⽤writelines()函数,要求将传⼊的变量写成⼀个list:
writers.writelines([a, ',', b])
读写追加的主要区别,体现在open()函数中的mode参数上,关于open()的mode参数:
‘r’:读
‘w’:写,覆盖写
‘a’:追加
‘r+’ == r+w(可读可写,⽂件若不存在就报错(IOError))
‘w+’ == w+r(可读可写,⽂件若不存在就创建)
‘a+’ ==a+r(可追加可写,⽂件若不存在就创建)
对应的,如果是⼆进制⽂件,就都加⼀个b就好啦:
‘rb’  ‘wb’  ‘ab’  ‘rb+’  ‘wb+’  ‘ab+’
3.python将⽂件内容按照某列值重新排序
python实现将⽂件内容按照某⼀列内容的⼤⼩值(不局限于数值,也可以是字母顺序)重新排序。
eg:将下⾯的内容按照第⼀列进⾏排序:
代码:
print(''.join(sorted(open(''), key=lambda s: s.split('\t')[0], reverse=1)))
排序前:
orgs    腾讯
orgs    腾讯
name    阿⾥
name    美团
name    华为
name    京东
orgs    ⽹易
name    ⼩⽶
orgs    上海
排序后:
orgs    腾讯
orgs    腾讯
orgs    ⽹易
orgs    上海
name    阿⾥
name    美团
name    华为
name    京东
name    ⼩⽶
⽂本排序后保存到txt⽂件中:
# ⽂本排序并保存
output_file = './'
output_file_sort = './'
with open(output_file_sort, 'a') as writersort:
writersort.write(''.join(sorted(open(output_file), key=lambda s: s.split('\t')[0], reverse=1)))
4.内容去重
1.⼩⽂件去重实现
第⼀步,读取⽂件每⼀⾏,并处理掉换⾏符
writelines()方法将什么写入文件第⼆步,将⽂件内容去重
第三步,写到新⽂件⾥
demo:
def file_remove_same(input_file, output_file):
"""
针对⼩⽂件去重
:param input_file: 输⼊⽂件
:param out_file: 去重后出⽂件
:return:
"""
with open(input_file, 'r', encoding='utf8') as f, open(output_file, 'a', encoding='utf8') as ff:
data = [item.strip() for item adlines()]  # 针对最后⼀⾏没有换⾏符,与其他它⾏重复的情况        new_data = list(set(data))
ff.writelines([item + '\n' for item in new_data if item])  # 针对去除⽂件中有多⾏空⾏的情况
2.⼤⽂件⼏⼗个G
就不能加载到内存中了,强⾏加载到内存中直接报内存错误
解决⽅案:
将⽂件按⾏读取,根据内容⽣成⼀个指纹(md5值或者其他唯⼀可识别的值),将指纹存集合中,当逐⾏读取的过程中判断集合中是否已经含有该⾏元素的指纹。如果指纹没有添加到集合中,则添加指纹到集合中并将此⾏追加输出到输出⽂件中。如果指纹已经在集合中了,说明此⾏与上⾯的某⼀⾏重复。
demo:
def gen_md5(data):
"""
⽣成md5
:param data: 字符串数据
:return:
"""
md5 = hashlib.md5()
md5.de('utf-8'))
return md5.hexdigest()
def big_file_remove_same(input_file, output_file):
"""
针对⼤⽂件⽂件去重(将⽂件⽂件写在⼀⾏的,没有办法去重)
:param input_file:
:param output_file:
:return:
"""
finger_print_set = set()
with open(input_file, 'r', encoding='utf8') as f, open(output_file, 'w', encoding='utf8') as ff:
for line in f:
line_string = line.strip()
finger_print = gen_md5(line_string)
if finger_print not in finger_print_set:
finger_print_set.add(finger_print)
ff.write(line)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。