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('\n').split(',')
15             print(str1)
16             # print(type)
17             fw.write("%s_%s,%s,%s,%s\n"%(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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM