Python files and tuples

Source: Internet
Author: User

    • Python file operations

It's a lot easier to do than files in Java,python.

Python Gets the folder where the current file resides:

Os.path.dirname (__file__)

Wrote a tool class to generate files under the current folder, so it's easy to

class Util ():     """ Tool Class """     @classmethod    def  Get_file_url (CLS, file_name):         "" " Gets the path of the current folder "" "        return os.path.join (os.path.dirname (__file__), File_ Name

Writes data to a file, W represents write, writes to

MyFile = open ("a.txt""w") myfile.write (" Hello2 world \ n " ) myfile.write ("good bye \ n")

Open file to view content as

If you are not working on the file after writing the file, remember to close the file and develop a good habit.

MyFile. Close ()

General file reads are placed in the try-except block, where the file is closed in Finally, so that the file will always be closed.

Read file

 myfile = open (Util.get_file_url ( " a.txt  ), "   R   " )   Print    first row   ", Myfile.readline () #   Read the first line  print  "   second row  , Myfile.readline ()  #   Read the second line  print   "  all rows  , Myfile.read () 
The ReadLine () method reads a row in the file one time, because the file has only 2 rows, so there is no more data to read after 2 ReadLine (), and the Read () method reads all the contents of the file into a string. If you want to speak the file pointer reset
To the first place, you can use the following methods
MyFile. Seek (0) # Reset the file to the first place

The Read () method allows you to specify the size of the reading bytes, such as read (6)

MyFile = open (Util.get_file_url ("aaa.xxx"),'r'= Myfile.read (6) # aaa.xxx content is "Hello", read 6 bytes can just read the string, a Chinese 3 bytes

Using iterators to read files

iterator = open (Util.get_file_url ("aaa.xxx"),'r')  for inch iterator:     Print Line

Reading a file to a list of strings

lines = Myfile.readlines () # Save each line of the file as an element in the list
    • Storing Python's soundtrack objects with pickle
classPerson (object):def __init__(Self, name="', age=0): Self.age=Age Self.name=namedef __str__(self):returnself.name+" -- "+str (self.age) P= Person ('Zhangsan', 24) P.sex='male'p.salary= 12000#save an object to a fileTo_file = open (Util.get_file_url ("Aaa.txt"),'WB') Pickle.dump (p, To_file) To_file.close ()PrintP.name#The object that will be stored in the file load inFrom_file = open (Util.get_file_url ("Aaa.txt"),'RB') # RB means reading the binary file person=pickle.load (from_file)PrintPerson
    • Tuple Operations (tuple)

Tuple existence Group if you provide integrity for the list, tuples are immutable and you can ensure that they are not modified by another reference in your program. It is similar to constants in other languages.

Tuples are common in Python for tuple types:

#Tuple definitionTuple1 = ()#an empty tupleTuple2 = (1,)#A tuple with 1 elementsInt1 = (1)#A variable that contains a single elementTuple4 = (1, 2, 3, 4,2)#traversing tuples forTupinchtuple4:PrintTupPrint '*'* 55#Gets the element that specifies the subscriptPrintTuple4[2]#gets the subscript of the specified numberPrintTuple4.index (4)#gets the number of occurrences of the specified valuePrintTuple4.count (2)PrintTuple4[1:3]#contains left without right
    • Introduction to references and copies in the Python list

Everything in Python is an object, and the assignment is just a copy of the reference. As an example:

>>> list1=[1,2,3,4]>>>Printlist1[1, 2, 3, 4]>>> x =List1>>>Printx[1, 2, 3, 4]>>> list1[1]='ABC'>>>Printlist1[1,'ABC', 3, 4]>>>Printx[1,'ABC', 3, 4]

If there are other object-oriented programming experience is not difficult to understand, then how to fully assign the List1 list to x, we can use the following methods

>>> x = list (list1)  (can also x = list1[:])print  x['ABC ', 3, 4]print  list1[1, 2, 3, 4]print  x[' /c14>ABC', 3, 4]

For the dict type, you can use the following method to achieve a complete copy

>>> Dict1 = {"a": 1,"b": 2}>>> Dict2 = Dict1.copy ()

Note: Only top-level copies are generated by copy and list () or list1[:], and nested data cannot be assigned. As an example:

>>> L = [1, 2, 3]>>> Dict1 = {"List": L}>>> tuple5 =(Dict1.copy (),)>>>PrintTuple5 ({'List': [1, 2, 3]},)>>> L[0] ="a">>>Printl['a', 2, 3]>>>PrintTuple5 ({'List': ['a', 2, 3]},)

If you want a deep copy of the results, you need to use the following method

Import= copy.deepcopy (tuple5) #此方法将会进行深层次拷贝

All right, let's get this done.

Python files and tuples

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.