"Python core Programming" notes

Source: Internet
Author: User

The Create file (maketextfile.py) script reminds the user to enter a file name that does not yet exist, and then the user enters each line of the file, and then writes all the text to the text file

1 #!/usr/bin/env python 2  3 ' maketextfile.py--creat text file ' 4  5 import os 6 ls = os.linesep 7  8 # get Fil  E name 9 while true:10 if Os.path.exists (fname):          #不存在返False, there is a return True11      print "ERROR: '%s ' already exists"% fname12  Else:13       break14 #get file content (text) lines16 all = []17 print] \nenter lines ('. ' by itself to quit). \ n "18 19 #loop until user terminates input while true:21      entry = raw_input (' > ')      if entry = = '. '  :           break24      else:25           all.append (entry) #write lines to file with proper line-ending28 fobj = open (fname, ' W ') fobj.writelines (['%s%s '% (X,ls) for x]) #列表解析, write each row (each element) in the list to a file, two%s is a string and each line terminator is fobj.close32 print ' D one! '

File read and display (readtextfile.py)

1 #!/user/bin/env python 2  3 ' readtextfile.py--read and display text file ' 4  5 # get filename 6 fname = Raw_inpu T (' Enter filename ') 7 print          #隔开提示和文本 8 # Attempt to open file for reading 9 try:10      fobj = open (fname, ' R ') one EXCEP T IOError, e:12      print "* * * File Open error:", E13 else:14      # dispaly content to the screen15 for      Eachline in FOB J16           Print eachline,17      fobj.close ()

"Python core Programming" notes

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.