python3中 for line1 in f1.readlines():,for line1 in f1:,循环读取一个文件夹

循环读取一个文件:

fr.seek(0)

fr.seek(0, 0)

 概述

seek() 方法用于移动文件读取指针到指定位置。

语法

seek() 方法语法如下:

fileObject.seek(offset[, whence])

参数

  • offset -- 开始的偏移量,也就是代表需要移动偏移的字节数

  • whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。

 1 def another_save():
 2     year_list=['00A','00B','01A','01B','01C',
 3     '02A','02B','03A','03B','04A','04B','05A','05B',
 4     '06A','06B','07A','07B','08A','08B','09A','09B',
 5     '10A','10B','11A','11B','12A','12B','13A','13B',
 6     '14A','14B','15A','15B','16A','16B','17A']
 7     # p1=r""
 8     fr=open("./new/b4/b4_0065.txt")
 9     fw=open("./new/b4/b4_new.csv",'a')
10     for i in range(len(year_list)):
11         j=40001
12         for line in fr.readlines():
13             print(type(line))
14             str1=line.strip('
').split(',')
15             print(str1)
16             # print(type)
17             fw.write("%s_%s,%s,%s,%s
"%(year_list[i],j,str1[0],str1[1],year_list[i]))
18             j=j+1
19         fr.seek(0)

循环读取一个文件:

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()
原文地址:https://www.cnblogs.com/smuxiaolei/p/7380985.html