The following is a few of their own written to the file operation of the small program, which involves file operations, lists (collections, dictionaries) and other applications. For example, read a row of data from a file. Store them in the list, and then manipulate the list. If you remove the repeated items inside. Sort operations.
It is common to manipulate the lines in a file:
#这里列出两个经常使用的方法
- Method : Read all rows at once
>>> f = file (' 1.txt ') >>> while 1:lines = F.readlines () if not lines:breakfor line in Lines:print line
- Method: A row of rows reads
>>> f = file (' 1.txt ') >>> while f:line = F.readline () If Len [line] = = 0:breakelse:print line,
Common list-to-repeat operations:
- Method 01: Function Processing
#列表中值超过1者表示有反复则删除, for example:
#列表顺序 ==> Change
>>> List1.count (3) #元素值为3的个数: 2 2>>> def removedup (LST): For x in Lst:if lst.count (x) >1:del LST [Lst.index (x)]>>> lst = [1,3,2,4,3]>>> removedup (LST) >>> lst[1, 2, 4, 3]
- Method 02: General Methods
#建新空列表, iterate through the original list. If you are not in the new empty list, join
#列表顺序 ==> unchanged
>>> List1 = [1,3,2,4,3]>>> List2 = []>>> for i in List1:if I not in list2:list2.append (i) >&G T;> list2[1, 3, 2, 4]
- Method 03: Dictionary Methods
#利用字典key值的唯一性, and the Fromkeys () and keys () method inside
>>> List1 = [1,3,2,4,3]>>> List2 = {}.fromkeys (list1). Keys () >>> list2[1, 2, 3, 4]
- Method 04: Collection method
#集合能去除列表中反复项
#列表顺序 ==> Change
>>> List1 = [1,3,2,4,3]>>> Set (list1) set ([1, 2, 3, 4])
- Method 05: Iteration Tools
#用itertools的迭代工具的groupby () method
#列表顺序 ==> Change
#先用集合, then use the sort, note key=list1.index. Control order
# List Order ==> change
>>> List1 = [1,3,2,4,3]>>> List2 = List (set (List1)) >>> List2.sort (Key=list1.index) >> > List2[1, 3, 2, 4]
Common for string inversion operations:
>>> s = ' Hello ' >>> l = List (s) >>> l[::-1][' o ', ' l ', ' l ', ' e ', ' H ']
- Method 02: General Practice
>>> def Rev (s): Str0 = ' l = len (s) -1while l >=0:STR0 + s[l]l- = 1return str0>>> s = ' A B C d ' >>> rev (s) ' d C B A '
- Method 03: List Inversion
>>> s = ' HELLO ' >>> l = list (s) >>> l.reverse () #列表reverse () method >>> '. Join (L) #用空字符串join列表 ' Olleh '
- Method 04:reduce function
>>> def Rev (s): return reduce (lambda x,y:y+x, s) #匿名函数和reduce函数结合使用 >>> s = ' AB CD ' >>> rev (s) ' DC BA '
Applet One: Extract the same part of two files
F1 = open ("1.txt", "r+") F2 = Open ("2.txt", "r+") F3 = Open ("3.txt", "w+") All1 = F1.readlines () #先拿文件1中全部行取出all2 = F2.readlines () #再拿文件2中全部行取出f1. Close () F2.close () for L1 in All1: for L2 in All2: if L1.strip () ==l2.strip (): #比較行中内容是否一样 F3.write (L2) else: continueelse: pass print "#" *40f3.close ()
Applet Two: reverse read file
If the contents of the Test.txt file to be read are as follows:
Python
Perl
Java
Shell
file1 = File (' test.txt ', ' R ') #打开文件句柄list1 = [] #用一个空列表用于存放每行的内容while True: Line = File1.readline () # Read List1.append (Line.strip ()) #去除字符串空格 If Len (line) = = 0: #假设没内容, interrupt break for L in List1[::-1] : #反向遍历. Then read it in turn print lfile1.close ()
Output Result:
Shell
Java
Perl
Python
Applet three: Operate on two text files
Requirements:
1. Remove repeated entries from each file
2. Find the same item in two files
3. Working with the collection in two files
4. Operation of the intersection in two files
#原始文件: Document 1, File 2f1 = file (' 1.txt ', ' r ') F2 = file (' 2.txt ', ' R ') #生成文件: Files 3, File 4, file 5, 6f3 = File (' same.txt ', ' w+ ') f4 = file (' Union.txt ', ' w+ ') f5 = file (' 1_diff.txt ', ' w+ ') f6 = file (' 2_diff.txt ', ' w+ ') #用空列表来存储原始文件的内容list1 = [] # Use an empty list to hold the contents of each row List2 = [] #用于存放文件2中的内容1_diff = [] #用于存放文件1中的去重部分2_diff = [] #用于存放文件2中的去重部分 # traverse two files while True:line1 = F1.readline () line2 = F2.readline () If Len (line1) ==0 or Len (line2) ==0:break else:list1.append ( line1) list2.append (line2) List1_uniq = set (list1) #排除第一个文件里反复的内容list2_uniq = set (list2) #注意应用集合排除反复的项目same = List1_uniq & List2_uniq #取交集union = List1_uniq | List2_uniq #取合集 # takes the intersection of two sets. Write to file 3 for I in Same:f3.write (i) #取两个集合的并集, write to file 4 for I in Union:f4.write (i) #取列表1中部分, intersection with common part for I in list1_ Uniq:if not I in Same:f5.write (i) #取列表2中部分, intersection with common part for I in list2_uniq:if not I in SAME:F6.W Rite (i) #关闭全部打开的文件句柄f1. Close () F2.close () F3.close () F4.close () F5.close () F6.close ()
Note: You can also use X-y to find the difference set of two sets
>>> X = set (' Spam ')
>>> Y = set ([' H ', ' A ', ' m '])
>>> x, y
(Set ([' A ', ' P ', ' s ', ' M ']), set ([' A ', ' h ', ' m '])
>>> X-y
Set ([' P ', ' s '])
Python applet for file manipulation and other