读写文件时应注意的问题包括:
1.字符编码
2.操作完成即时关闭文件描述符
3.代码兼容性
几种方法:
#!/bin/python3original_list1=[" "]original_list2=[" "]original_list3=[" "]original_list4=[" "]newlist1=[" "]newlist2=[" "]newlist3=[" "]newlist4=[" "]newtxt1=""newtxt2=""newtxt3=""newtxt4=""#first way to readlinef = open("duplicate_txt.txt","r+") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: original_list1.append(line) line = f.readline() f.close() #use "set()" remove duplicate str in the list# in this way,list will sort randomlynewlist1 = list(set(original_list1))#newlist1 = {}.fromkeys(original_list1).keys() #faster #rebuild a new txt newtxt1="".join(newlist1)f1 = open("noduplicate1.txt","w")f1.write(newtxt1)f1.close()####################################################################second way to readlinefor line in open("duplicate_txt.txt","r+"): original_list2.append(line)newlist2 = list(set(original_list2))newlist2.sort(key=original_list2.index) #sort#newlist2 = sorted(set(original_list2),key=l1.index) #other waynewtxt2="".join(newlist2)f2 = open("noduplicate2.txt","w")f2.write(newtxt2)f2.close()####################################################################third way to readlinef3 = open("duplicate_txt.txt","r") original_list3 = f3.readlines() #读取全部内容 ,并以列表方式返回 for i in original_list3: #遍历去重 if not i in newlist3: newlist3.append(i)newtxt3="".join(newlist3)f4 = open("noduplicate3.txt","w")f4.write(newtxt3)f4.close()####################################################################fourth wayf5 = open('duplicate_txt.txt',"r+") try: original_list4 = f5.readlines() [newlist4.append(i) for i in original_list4 if not i in newlist4] newtxt4="".join(newlist4) f6 = open("noduplicate4.txt","w") f6.write(newtxt4) f6.close()finally: f5.close()
结果:
去重前:
去重后(无序):
去重后(有序):
总结
这段下程序涉及文件读写操作以及链表List的操作,文章开头提到的几个问题,由于并没有使用中文,所以不关心编码,但这里还是要提一提:
f = open("test.txt","w")f.write(u"你好")
上面这段代码如果在python2中运行会报错
报错是因为程序没办法直接保存unicode字符串,要经过编码转换成str类型的二进制字节序列才可以保存。
write()方法会自动编码转换,默认使用ascii编码格式,而ascii不能处理中文,所以出现UnicodeEncodeError。
新闻热点
疑难解答