Python applets, file operations and other

Source: Internet
Author: User

Python applets, file operations and other

Below are several small programs written by myself for file operations, including file operations and the use of lists (collections and dictionaries. For example, read a row of data from a file, store it in the list, and then perform operations on the list, such as removing duplicate items and sorting.

Common Operations on the file row:

# Two common methods are listed here

Method 01: Read all rows at a time
>>> f = file('1.txt')>>> while 1:lines = f.readlines()if not lines:breakfor line in lines:print line

Method 02: read one row
>>> f = file('1.txt')>>> while f:line = f.readline()if len(line) == 0:breakelse:print line,

Common Operations on repeated items in the list:

Method 01: function processing

# If the value of 1 in the list is exceeded, it indicates that the list is deleted if there are duplicates. For example:

# List order ==> change

>>> List1.count (3) # number of elements with a value of 3: 2 2 >>> def removeDup (lst): for x in lst: if lst. count (x)> 1: del lst [lst. index (x)] >>> lst = [1, 3, 2, 3] >>> removeDup (lst) >>> lst [1, 2, 4, 3]

Method 02: General Method

# Create an empty list and traverse the original list. If the list is not in the new empty list, add

# List order ==> unchanged

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

Method 03: Dictionary Method

# Use the uniqueness of the dictionary key value and the fromkeys () and keys () methods in it

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

Method 04: Set Method

# Duplicate items in the list can be removed from the set

# List order ==> change

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

Method 05: iterative tools

# Use the groupby () method of the itertools iteration Tool

# List order ==> change

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

Method 06: Index sorting

# First use a set and then sort it. Note that key = list1.index controls the 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 string inversion operations:

Method 01: List slice
>>> 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: reverse list
>>> S = 'hello' >>> l = list (s) >>> l. reverse () # list reverse () method> ''. join (l) # use an empty string to join the 'olleh' list'
    Method 04: reduce Function
    >>> Def rev (s): return reduce (lambda x, y: y + x, s) # combination of anonymous functions and reduce functions >>> s = 'AB Cd' >>> rev (s) 'DC Ba'
    Applet 1: extract the same part of the two files

    F1 = open ("1.txt"," r + ") f2 = open (" 2.txt", "r +") f3 = open ("3.txt"," w + ") all1 = f1.readlines () # first retrieve all rows in file 1 all2 = f2.readlines () # Then retrieve all rows in file 2 f1.close () f2.close () for l1 in all1: for l2 in all2: if l1.strip () = l2.strip (): # compare whether the content in the row is the same as f3.write (l2) else: continueelse: pass print "#" * 40f3. close ()
    Applet 2: reverse reading of Files

    The content of the test.txt file to be read is as follows:

    Python
    Perl
    Java
    Shell

    File1 = file('test.txt ', 'R') # open the file handle list1 = [] # use an empty list to store the content of each row while True: line = file1.readline () # Read list1.append (line. strip () # Remove the string space if len (line) = 0: # if there is no content, the break for l in list1 [:-1]: # reverse traversal, print lfile1.close ()
    Output result:

    Shell
    Java
    Perl
    Python


    Applet 3: operate on two text files

    Requirements:

    1. Remove duplicate items from each file

    2. Find the same item in the two files

    3. Operate the collection of the two files

    4. Operate the intersection of the two files

    # Original file: File 1, file 2f1 = file('1.txt ', 'R') f2 = file('2.txt', 'R') # generate a file: file 3, file 4, File 5, file 6f3 = file('same.txt ', 'W +') f4 = file('union.txt ', 'W +') f5 = file('{diff.txt ', 'W +') f6 = file('2_diff.txt ', 'W + ') # use an empty list to store the content of the original file list1 = [] # use an empty list to store the content of each row list2 = [] # use it to store the content of file 2 paidiff = [] # used to store the deduplication part 2_diff = [] # used to store the deduplication part in file 2 # traversing 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) listparts uniq = set (list1) # exclude repeated content in the first file list2_uniq = set (list2) # note that duplicate items are excluded from the application set. same = listdomainuniq & list2_uniq # intersection union = listdomainuniq | list2_uniq # collection # intersection of two sets, which is written into file 3 for I in same: f3.write (I) # Take the union of the two sets and write it into file 4 for I in union: f4.write (I) # Take the part in List 1, take the intersection with the common part for I in listparts uniq: if not I in same: f5.write (I) # Take the part in List 2 and take the intersection with the common part for I in list2_uniq: if not I in same: f6.write (I) # Close all open file handles f1.close () f2.close () f3.close () f4.close () f5.close () f6.close ()



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.