Python 小程式,對檔案操作及其他,

來源:互聯網
上載者:User

Python 小程式,對檔案操作及其他,

下面是自己寫的幾個對檔案操作的小程式,裡面涉及到檔案操作,列表(集合,字典)的運用等。比如說,從檔案中讀取一行資料,分別存放於列表中,再對列表進行操作,如去掉裡面的重複項,排序等操作。

常見對檔案中行進行操作:

#這裡列出兩個常用的方法

  • 方法01: 一次性讀取所有行
>>> f = file('1.txt')>>> while 1:lines = f.readlines()if not lines:breakfor line in lines:print line

  • 方法02: 一行行讀取
>>> f = file('1.txt')>>> while f:line = f.readline()if len(line) == 0:breakelse:print line,

常見對列表去重複項操作:

  • 方法01: 函數處理

#列表中值超過1者表示有重複則刪除,比如:

#列表順序==>改變

>>> 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]

  • 方法02: 常規方法

#建新空列表,遍曆原始列表,如果不在新空列表中,則添加

#列表順序==>不變

>>> list1 = [1,3,2,4,3]>>> list2 = []>>> for i in list1:if i not in list2:list2.append(i)>>> list2[1, 3, 2, 4]

  • 方法03: 字典方法

#利用字典key值的唯一性,及裡面的fromkeys()及keys()方法

>>> list1 = [1,3,2,4,3]>>> list2 = {}.fromkeys(list1).keys()>>> list2[1, 2, 3, 4]

  • 方法04: 集合方法

#集合能去除列表中重複項

#列表順序==>改變

>>> list1 = [1,3,2,4,3]>>> set(list1)set([1, 2, 3, 4])

  • 方法05: 迭代工具

#用itertools的迭代工具的groupby()方法

#列表順序==>改變

>>> import itertools>>> lst = [1, 3, 2, 4, 3]>>> lst.sort()>>> it = itertools.groupby(lst)>>> for k,g in it:print k1234 

  • 方法06: 索引排序

#先用集合,再用排序,注意key=list1.index,控制順序

#列表順序==>改變

>>> list1 = [1,3,2,4,3]>>> list2 = list(set(list1))>>> list2.sort(key=list1.index)>>> list2[1, 3, 2, 4]

常見對字串反轉操作:

  • 方法01: 列表切片
>>> s = 'Hello'    >>> l = list(s)>>> l[::-1]['o', 'l', 'l', 'e', 'H']

  • 方法02: 常規做法
>>> 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'

  • 方法03: 列表反轉
>>> s = 'HELLO'>>> l = list(s)>>> l.reverse()  #列表reverse()方法>>> ''.join(l)   #用Null 字元串join列表'OLLEH'
  • 方法04: reduce函數
>>> def rev(s):return reduce(lambda x,y: y+x, s) #匿名函數和reduce函數結合使用>>> s = 'AB CD'>>> rev(s)'DC BA'
小程式一: 提取兩個檔案中相同部分

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()
小程式二: 反向讀取檔案

假如要讀取的test.txt檔案內容如下:

Python
Perl
Java
Shell

file1 = file('test.txt','r')   #開啟檔案控制代碼list1 = []                     #用一個空列表用於存放每行的內容while True:    line = file1.readline()    #按行讀取    list1.append(line.strip()) #去除字串空格    if len(line) == 0:         #如果沒內容,則中斷        break                     for l in list1[::-1]:          #反向遍曆,然後依次讀取出來    print lfile1.close()
輸出結果:

Shell
Java
Perl
Python


小程式三: 對兩個文字檔進行操作

要求:

1. 移除每個檔案中的重複項

2. 找出兩個檔案中的相同項

3. 操作兩個檔案中的合集

4. 操作兩個檔案中的交集

#原始檔案:檔案1,檔案2f1 = file('1.txt','r')f2 = file('2.txt','r')#組建檔案:檔案3,檔案4,檔案5,檔案6f3 = file('same.txt','w+')f4 = file('union.txt','w+')f5 = file('1_diff.txt','w+')f6 = file('2_diff.txt','w+')#用空列表來儲存原始檔案的內容list1  = []  #用一個空列表用於存放每行的內容list2  = []  #用於存放檔案2中的內容1_diff = []  #用於存放檔案1中的去重部分2_diff = []  #用於存放檔案2中的去重部分#遍曆兩個檔案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 #取合集#取兩個集合的交集,寫入檔案3中for i in same:       f3.write(i)  #取兩個集合的並集,寫入檔案4中for i in union:      f4.write(i)  #取列表1中部分,與共同部分取交集for i in list1_uniq:    if not i in same:        f5.write(i)#取列表2中部分,與共同部分取交集       for i in list2_uniq:    if not i in same:        f6.write(i)#關閉所有開啟的檔案控制代碼f1.close()f2.close()f3.close()f4.close()f5.close()f6.close()






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.