Python 0 Basic Learning-Fundamentals 5-Collections and files

Source: Internet
Author: User

Collection: a special list

    • The data in the collection is not duplicated
    • You can test the relationship between two sets of data: intersection, set, and difference set
    • The data in the collection is unordered

1. Create a Collection

# ---------------------------Method 1---------------------list1=[1,2,3,4,5]list2=Set (list1)  Print(list2)         # Execution Result: {1, 2, 3, 4, 5}, curly brace is the identity of the collection print(Type (LIST2))   # execution Result: <class ' Set ' > # --------------------------Method 2-----------------------List3=set ([2, 4, 6, 8, 10])

2. Set Relationship Test

1) Seek the intersection

Print (List2.intersection (LIST3)) Print (list2&list3) # Execution Result: {2, 4}

2) Seek and remove weight

Print (List2.union (LIST3)) Print (list2| list3) # execution Results: {1, 2, 3, 4, 5, 6, 8, ten}

3) Differential set: 1 have, 2 no

Print (List2.difference (LIST3)) Print (list2-list3) # Execution Result: {1, 3, 5}

4) Symmetric difference set: set-intersection

Print (List2.symmetric_difference (LIST3)) Print (list2^list3) # Execution Result: {1, 3, 5, 6, 8, ten}

5) Relationship Judgment

Print (List2.issubset (LIST3), List2.issuperset (LIST3)) # Determines whether List2 is a subset of LIST3; Determines whether List2 is the parent set of List3 # execution Result: false false Print (List2.isdisjoint (LIST3)) # two set without intersection returns TRUE, otherwise false

3. Changes to the collection

List2.add (+)                     # Add a item in the collection #  list2.remove (104)                  #  Removes an item in the collection List2.pop ()                        # arbitrarily deletes an item list2.discard (103)                 # exists then deletes, does not exist then ignores 

TIP:

The following methods determine whether an element exists, for dictionaries, lists, collections, strings

Print  in List2)              # returns TRUE or false

File

1. Open the file and read the contents of the file

#Method 1Data=open ("file1", encoding="Utf-8"). Read ()#If you do not label the encoding format, it will be opened using the operating system default encoding. Windows default encoding format is GBKPrint(data)#Print the entire contents of a file#method 2; To avoid constantly invoking the open method to create a file object, use Method 2 as much as possibleF=open ("file1", encoding="Utf-8")#To create a file handleData=F.read ()Print(data)#Print the entire contents of a filedata1=F.read ()Print(DATA1)#print empty. Reason: When reading data, the cursor of the file has been moved to the bottom of the fileF.close ()

2. File read and write mode

1) W: write mode, cannot read file

F=open ("file2","w", encoding="utf-8  ")           # Create a new file file2; If the file already exists, it will overwrite the previous f.write (" la la la, I'm a little connoisseur of the newspaper")      #  Write content to the newly created file f.close ()

2) A: Append mode, cannot read file

F=open ("file2","a", encoding="utf-8             # # # # # Open an existing File2 file f.write (" go to the morning and sell the newspaper \ \ \ \ \ \" run and call \ \")        # Append the content to the end of the file F.close ()

3) R: Read-only mode, only read files, cannot write; If read-write mode is not specified, the default is R

#reads the contents of the file as a list, one element for each behavior, and the method consumes a lot of memory and tries not to useF=open ("file1","R", encoding="Utf-8")Print(F.readlines ()) F.close ()#Loop ReadF=open ("file1","R", encoding="Utf-8") forIinchRange (5):    Print(F.readline ()) F.close ()#the most efficient method, the recommended useF=open ("file1","R", encoding="Utf-8") forLineinchF:Print(line) f.close ()

4) r+: Can read the file, can be written in an append way

F=open ("file2","r+", encoding="utf-8 " )print(F.readline ())                        # can read the file f.write (" today's news really good \ n  ")             # starts writing the file from the last side of the file, writes it as an append, and moves the cursor without f.close ()

5) w+: First create a new file, then write

F=open ("file1","w+", encoding="utf-8 " f.write (" la la la, I'm a little connoisseur of the newspaper, not till Dawn to sell the newspaper ") F.seek (6) F.write (  "123")      # will start writing from where the cursor is, but will be written in insert mode, overwriting the following characters F.close ()

6) RB:

    • Read files in binary format
    • Cannot specify encoding parameters, usually used for network transmission, video files, file cross-platform open and other functions

7) WB: must be converted into binary encoding for writing

3. File Handle Location

F=open ("file1","R", encoding="Utf-8")Print(F.tell ())#Print file handle position, initial position is 0F.readline ()Print(F.tell ())#The handle reaches the second line, and in this example the value is---> The number of characters in the first row of charactersPrint(F.read (2))#start at a subordinate, read two charactersf.seek (0)#Handle Returns the beginning of the filef.close ()

4. Modification: There are only two ways

    • Load all into memory, write it after the modification is complete
    • Read it, change it, save it in a new file.
F=open ("file2","R", encoding="Utf-8") F_new=open ("File3","W", encoding="Utf-8") forLineinchF:if "reported" inchLine:line=line.replace ("reported","Newspapers") F_new.write (line) F.close () f_new.close ()

5. Other

Print(f.encoding)#Print File EncodingPrint(F.name)#Print file nameF.truncate ()#empty the file, erase it from the beginning, and move the cursor without using#F.flush (): Forces the contents of memory to be flushed to the hard disk, often for write-sensitive data such as amounts#when a refresh is not enforced, the system waits for a certain amount of data to be written to the hard disk when the memory is stored#Simulation Process BarImportSys, time forIinchRange (20): Sys.stdout.write (">") Sys.stdout.flush () Time.sleep (0.5)

6. With statement: The file is automatically closed after execution is complete

With open ("file2","R", encoding="Utf-8") as F:Print(F.readline ()) with open ("file2","R", encoding="Utf-8") as F1,open ("File3","R", encoding="Utf-8") as F2:Print(F1.readline ())Print(F2.readline ())

Python 0 Basic Learning-Fundamentals 5-Collections and files

Related Article

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.