Python applet, for file operations and other

Source: Internet
Author: User

The following is a few of their own written on the file operation of the small program, which involves file operations, lists (collections, dictionaries) and other applications. For example, reading a row of data from a file, storing it in a list, and then manipulating the list, such as removing duplicates, sorting, and so on.

Common actions for a row in a file:

#这里列出两个常用的方法

    • Method : Reads 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 deduplication operations:

    • Method 01: Function Processing

#列表中值超过1者表示有重复则删除, such as:

#列表顺序 ==> 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 it is not in the new empty list, add

#列表顺序 ==> 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

    • Method 06: Index Sorting

#先用集合, then 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:

    • Method 01: List slices
>>> 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 out    print lfile1.close ()
Output Result:

Shell
Java
Perl
Python


Applet three: Operate on two text files

Requirements:

1. Removing duplicates from each file

2. Find the same item in two files

3. Working with two files in a collection

4. Manipulating the intersection of 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, writes to file 3 for I in Same:f3.write (i) #取两个集合的并集, writes to file 4 for I in Union:f4.write (i) #取列表1中部 The intersection of the list1_uniq:if with the common part for I in the Same:f5.write (i) #取列表2中部分, the intersection with the common part for I in List2_uniq:if N OT i in Same:f6.write (i) #关闭所有打开的文件句柄f1. Close () F2.close () F3.close () F4.close () F5.close () F6.close ()



Python applet, for file operations and other

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.