Python function initial knowledge and file manipulation

Source: Internet
Author: User

File operations

Open File: 文件句柄  =open(‘文件路径‘‘模式‘)

Mode of open File
W #以写的方式打开 (unreadable, does not exist then created, exists delete content) a #以追加的模式打开 (readable, nonexistent then created, append content exists) r                     #以只读模式打开 "+" means you can read and write a file r+ #以读写的模式打开w + #以读写的模式打开 A +     #以读写的模式打开 "B" means processing the binary file RB #以二进制模式读打开 WB #以二进制写模式打开 AB #以二进制追加模式打开 rb+ #以二进制读写模式打开wb + #以二进制读写模式打开ab + #以二进制读写模式打开 "U" means you can convert \ r \ r \ n \              N (same as R or r+ mode) rur+u3 fp = open ("Test.txt", W) fp.close #关闭文件, habit, open the file, after use, remember to close, otherwise it may be reported Valueerrorfp.fileno #返回一个文件描述符, use the underlying operation to request system I/O operations Fp.flush #刷新文件内容缓冲区fp. Isatty #文件是否是一个终端设备文件 (Unix system) F P.next #获取下一行的数据, there is no error.                The for I in File:print I.strip () is the call to this next () method Fp.read ([size]) #读取指定字节数的数据 in bytes fp.readline ([size]) #读一行, if size is defined, it is possible to return a portion of Fp.readlines ([size]) in a row #把文件每一行作为一个list的一个成员 and return the LISt.                                         Internal or call ReadLine () method Fp.seek (Offset[,whence]) #将文件操作移动到offset的位置, this offset is generally relative to the beginning of the file calculation, generally an integer,                                         #0 calculate from the beginning #1 start at the current position #2 never see the end of the Fp.tell #告诉文件操作的当前位置, calculate the Fp.truncate #把文件裁成规定的大小 starting at the beginning, and the default is to crop to the current                          Location of the file action tag Fp.write #往文件里面写内容fp. Writelines #将一个字符串列表写入文件fp. Closed                  #关闭文件fp. Encoding fp.errors Fp.mode Fp.name
Fp.newlines
Fp.softspace

  

 With application1, in order to avoid opening the file, forget to close, you can manage the context:
With open ("Log.txt", "R") as F:                #只读的方式打开文件, alias is F for line in    F:                                                  print line                            #打印每一行                                              # Internal automatically shuts down and frees file resources after execution is complete

  

2, after python2.7, with also supports the simultaneous management of multiple file contexts
With open ("Log1.txt") as Obj1  , open ("Log2.txt") as  Obj2: #可以进行复制的操作 for line in    obj1:         Obj2.write (line)  

  

python reads files in several poses per line
  1. File = Open ("A.log", "R") Whiletrue: Line        = File.readline ()        If the line: Break        Passimport fileinputfile = Open ("A.log", "R") for line in Fileinput.input ("A.log"):        passfile = open ("A.log", "R") Whiletrue:        lines = File.readlines (100000)        If not lines:                broke        for line in lines:                passfile = open ("A.log", "R")                         # Equivalent  to with open ("A.log", "R") as F: # for Line in F: For line in                     file:                                #                           Pass             passfile = open ("A.log", "R")                         #已经废弃for Line in File.xreadlines ():        

      

  2.                                  
Custom functions have always followed process-oriented programming, similar to Shell scripting, by piling up some commands to handle things, according to the business's Logitech top-to-bottom implementation capabilities
    1. Whiletrue:    If CPU utilization > 90%:        #发送邮件提醒        Connect mailbox server        Send mail        off connection      if hard disk use space > 90%:        #发送邮件提醒        Connect mailbox server        Send mail        close connection      If memory consumption > 80%:        #发送邮件提醒        Connect mailbox server        Send mail        close connection

      Look at the above code, you can extract the contents of the IF statement common, as follows:

def send mail (content)    #发送邮件提醒    connect a mailbox server to    send mail    off connection while  True:      If CPU utilization > 90%:        send mail (' CPU alert ')      if HDD uses space > 90%:        send mail (' HDD alert ')      if memory consumption > 80%:      Send mail ("Memory Alarm")
For the two implementations, the second display is better than the first reuse and readability, which is also the difference between functional programming and process-oriented programming.       function: A function code is encapsulated in a function, it will not need to be repeated later, only need to call the function to    Object-oriented: classify and encapsulate functions to make development "faster, stronger ..." " 
Functional Programming The most important thing is to enhance the reusability and readability of code         definition and use of functions
    1. def  foo (args):    print "hello,world!"    return Argsret = foo (name) print RET

        

Note: The above is called a function, the wrong write       foo (name) changed to foo ("name") Why should arguments be used for parameters of functions?
    1. def send mail (message content)                  #邮件内容为参数 # Send mail reminder to connect mailbox server send mail close connection whiletrue:if CPU utilization >90%: Send Message ("CPU alarm up. If the hard disk uses space >90%: Send mail ("hdd alarm up.") If memory consumption >80%: Send Message ("Memory alarm is up.") ")
types of parameters in a function1, general parameters
    1. def func (args):    print Argsfunc ("BUDONGHSU")

        

 2, default parameters
    1. def func (Name,age =18):    print "%s:%s"% (Name,age) func ("Budongshu", +) func ("Budongshu") Run Result: Budongshu : 19budongshu:18

        

NOTE: The default parameter is placed in the last face of the parameter list
 3, dynamic parameters
    1. def func (*arg):              #可以接收列表, tuple, string    print arg execution way one name =[1,2,3,4]func (name) name = ("A", "B") func (name) execution mode two func (" BDS ", 123)  execution Result:                           #返回的是一个元组 ([1, 2, 3, 4],) ((' A ', ' B '),) (' BDS ', 123)

        

    1. def func (**kwargs):                 #可以接收字典   

        

    1. def foo (*arg,**kwargs):        print ' arg = ', arg        print ' Kwargs = ', Kwargs        

        

    1.  运行结果:
    2. arg =  (1,2,3,4) Kwargs ={}-------------------------arg =  () Kwargs ={' A ': 1, ' C ': 3, ' B ': 2}--------------------- ----arg =  (1,2,3,4) Kwargs ={' A ': 1, ' C ': 3, ' B ': 2}-------------------------arg =  (' A ', 1,none) Kwargs ={' A ': 1, ' C ': 3, ' B ': ' 2 '}-------------------------

        

Python e-mail#!/usr/bin/env python#conding: Utf-8 *_*Import SmtplibFrom email.mime.text import MimetextFrom email.utils import formataddr  msg = Mimetext (' My name is Budongshu ', ' plain ', ' utf-8 ')msg[' from '] = FORMATADDR (["Budongshu", ' [email protected] ')msg[' to ' = FORMATADDR (["QQ", ' [email protected] ')msg[' Subject ' = "Hello hero subnet" Server = Smtplib. SMTP ("smtp.126.com", +)server.login ("[Email protected]", "Your password")server.sendmail (' [email protected] ', [' [email protected] ',], msg.as_string ())server.quit ()Detailed test:         



From for notes (Wiz)



List of attachments
    • 1.jpg
    • 2.jpg
    • 2015-12-15_210352.png
    • 3.png
    • 4.png
    • 4_2.png
    • Python sends mail. png

Python function initial knowledge and file manipulation

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.