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()