python3中 for line1 in f1.readlines():,for line1 in f1:,循环读取一个文件夹
Posted 懵懂的菜鸟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3中 for line1 in f1.readlines():,for line1 in f1:,循环读取一个文件夹相关的知识,希望对你有一定的参考价值。
1 #-*- encoding:utf-8 -*- 2 3 class loadDatas(object): 4 def __init__(self): 5 self.path=‘./data‘ 6 def load_compare(self): 7 l1={} 8 f1=open(self.path+‘/95b.txt‘,encoding=‘utf-8‘) 9 l2={} 10 f2=open(self.path+‘/05b.txt‘,encoding=‘utf-8‘) 11 f=open(self.path+‘/1.txt‘,‘a‘) 12 # w2=open(‘./data/1.txt‘,‘a‘) 13 14 # flag=1 15 str1=[] 16 # print(type(str1)) 17 for line2 in f2.readlines(): 18 19 (tag2,name)=line2.strip().split(" ") 20 flag=0 21 for line1 in f1.readlines(): 22 (tag1,name)=line1.strip().split(" ") 23 print(tag1) 24 if tag2==tag1: 25 print("a") 26 flag=0 27 break 28 else: 29 print(‘d‘) 30 flag=1 31 # break 32 # print("aa") 33 if flag==1: 34 # print("aa") 35 str1.append(line2) 36 print(str1) 37 f.writelines(str1) 38 39 f1.close() 40 f2.close() 41 f.close() 42 43 if __name__==‘__main__‘: 44 ld=loadDatas() 45 ld.load_compare()
结果:
ADR
a
[]
[Finished in 0.2s]
循环读取一个文件:
f1.seek(0)
1 #-*- encoding:utf-8 -*- 2 3 class loadDatas(object): 4 def __init__(self): 5 self.path=‘./data‘ 6 def load_compare(self): 7 l1={} 8 f1=open(self.path+‘/95b.txt‘,encoding=‘utf-8‘) 9 l2={} 10 f2=open(self.path+‘/05b.txt‘,encoding=‘utf-8‘) 11 f=open(self.path+‘/1.txt‘,‘a‘) 12 # w2=open(‘./data/1.txt‘,‘a‘) 13 14 # flag=1 15 str1=[] 16 # print(type(str1)) 17 # int i 18 for line2 in f2: 19 print(line2) 20 (tag2,name)=line2.strip().split(" ") 21 flag=0 22 for line1 in f1: 23 # 读完一次循环后,line1已经到底了,第2次循环便不进入; 24 # f1.readlines()只能进入一次,一次读取整个文件; 25 26 (tag1,name)=line1.strip().split(" ") 27 print(tag1) 28 if tag2==tag1: 29 print("a") 30 flag=0 31 break 32 else: 33 print(‘d‘) 34 flag=1 35 # break 36 # print("aa") 37 if flag==1: 38 # print("aa") 39 str1.append(line2) 40 f1.seek(0) 41 print(str1) 42 f.writelines(str1) 43 44 f1.close() 45 f2.close() 46 f.close() 47 48 if __name__==‘__main__‘: 49 ld=loadDatas() 50 ld.load_compare()
以上是关于python3中 for line1 in f1.readlines():,for line1 in f1:,循环读取一个文件夹的主要内容,如果未能解决你的问题,请参考以下文章
Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in(示例