《python核心編程》筆記

來源:互聯網
上載者:User

標籤:字串   adt   user   img   nat   line   att   quit   write   

建立檔案(makeTextFile.py)指令碼提醒使用者輸入一個尚不存在的檔案名稱,然後由使用者輸入檔案每一行,最後將所有文本寫入文字檔

 1 #!/usr/bin/env python 2  3 ‘makeTextFile.py -- creat text file‘ 4  5 import os 6 ls = os.linesep 7  8 # get file name 9 while True:10 if os.path.exists(fname):          #不存在返False,存在返True11      print "ERROR: ‘%s‘ already exists" % fname12 else: 13       break14 15 #get file content (text) lines16 all = []17 print "\nEnter lines (‘.‘ by itself to quit).\n"18 19 #loop until user terminates input 20 while True:21      entry = raw_input(‘>‘)22      if entry == ‘.‘:23           break24      else:25           all.append(entry)26 27 #write lines to file with proper line-ending28 fobj = open(fname, ‘w‘)29 fobj.writelines([‘%s%s‘ % (x,ls) for x in all])30 #列表解析,將列表中每行(每個元素)都寫入檔案,兩個%s分別是字串和每行結束符31 fobj.close32 print ‘DONE!‘

檔案讀取和顯示(readTextFile.py)

 1 #!/user/bin/env python 2  3 ‘readTextFile.py -- read and display text file‘ 4  5 # get filename 6 fname = raw_input(‘Enter filename‘) 7 print          #隔開提示和文本 8 # attempt to open file for reading 9 try:10      fobj = open(fname, ‘r‘)11 except IOError, e:12      print "*** file open error:",e13 else:14      # dispaly content to the screen15      for eachLine in fobj16           print eachLine,17      fobj.close()

 

《python核心編程》筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.