Chapter 9 Answers to exercises in Python core programming (1)

Source: Internet
Author: User

9-1. file filtering. display all lines of a file and ignore the lines starting with the #. This character is used

Comments of Python, Perl, TCL, and many other script files.

#filename:test9-1.pyf=open('F:\\test.txt','r')for eachline in f:    try:        if eachline.lstrip()[0]!='#':             print eachline,    except:        passf.close()

Additional question: handle comments not starting with the first character

#filename:test9-1.py#__doc__f=open('F:\\test.txt','r')for eachline in f:    if '#' in eachline:        r=eachline.find('#')        if r>0 :            #print eachline[r-1:r+2]            if eachline[r-1:r+2]!= r"'#'"  and eachline[r-1:r+2]!=r'"#"':                               print eachline[:r],            else:                print eachline,     else:        print eachline,    f.close()

9-4. File Access. Write a program that displays text files page by page. The system prompts you to enter a file name.
Line 25 of the file, pause and prompt the user to "press any key to continue.", press the key to continue.

Note: End of File Processing

def rbypage():    fname=raw_input("Enter filename:").strip()    fp = open(fname,'r')    while True:        lines=0        for p in range(25):            cline=fp.readline()            if cline!='':                lines+=1                print cline,        if lines<25:            print '\nfile is over'            break        info=raw_input("continue?(Y/N)").upper()        if info=='N':            break    fp.close()rbypage()

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.