<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      Python(Head First)學習筆記:四

      4 持久存儲:文件存儲、讀寫

         數據保存到文件:在學習的過程中出現了一個問題,老是報一個錯:SyntaxError: invalid syntax;

              這個是語法錯誤,后來搜了下才知道是python2.7和python3.5并不兼容,因為之前一直是在ubuntu的終端里

      寫這些簡單的實例,后來程序稍微大點就不方便了,就安裝了idle,用命令:sudo apt-get install idle,安裝完啟動后,

      載入python文件,然后運行發現是python2.7,然后逐行運行,發現報錯,而之前這些代碼都是沒問題的,后來重新安

      裝idle3,命令:sudo apt-get install idle3,然后啟動:idle3,運行實例代碼,沒有問題。

      實例一:

       1 Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
       2 [GCC 5.4.0 20160609] on linux
       3 Type "copyright", "credits" or "license()" for more information.
       4 >>> import os
       5 >>> os.getcwd()
       6 '/home/user'
       7 >>> os.chdir('/home/user/project/python_model/HeadFirstPython/chapter3')
       8 >>> os.getcwd()
       9 '/home/user/project/python_model/HeadFirstPython/chapter3'
      10 >>> man=[]
      11 >>> other=[]
      12 >>> try:
      13     data=open('sketch.txt')
      14     for each_line in data:
      15         try:
      16             (role,line_spoken)=each_line.split(':',1)
      17             line_spoken=line_spoken.strip()
      18             if role=='Man':
      19                 man.append(line_spoken)
      20             elif role=='Other Man':
      21                 other.append(line_spoken)
      22         except ValueError:
      23             pass
      24     data.close()
      25 except IOError:
      26     print('The datafile is missing!')
      27 
      28     
      29 >>> print(man)
      30 ['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
      31 >>> print(other)
      32 ["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]
      33 >>> 
      View Code

       以寫模式打開文件

        使用open()BIF打開磁盤文件時,可以指定訪問的模式,open()的幫助文件如下:

        1 help(open)
        2 Help on built-in function open in module io:
        3 
        4 open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
        5     Open file and return a stream.  Raise IOError upon failure.
        6     
        7     file is either a text or byte string giving the name (and the path
        8     if the file isn't in the current working directory) of the file to
        9     be opened or an integer file descriptor of the file to be
       10     wrapped. (If a file descriptor is given, it is closed when the
       11     returned I/O object is closed, unless closefd is set to False.)
       12     
       13     mode is an optional string that specifies the mode in which the file
       14     is opened. It defaults to 'r' which means open for reading in text
       15     mode.  Other common values are 'w' for writing (truncating the file if
       16     it already exists), 'x' for creating and writing to a new file, and
       17     'a' for appending (which on some Unix systems, means that all writes
       18     append to the end of the file regardless of the current seek position).
       19     In text mode, if encoding is not specified the encoding used is platform
       20     dependent: locale.getpreferredencoding(False) is called to get the
       21     current locale encoding. (For reading and writing raw bytes use binary
       22     mode and leave encoding unspecified.) The available modes are:
       23     
       24     ========= ===============================================================
       25     Character Meaning
       26     --------- ---------------------------------------------------------------
       27     'r'       open for reading (default)
       28     'w'       open for writing, truncating the file first
       29     'x'       create a new file and open it for writing
       30     'a'       open for writing, appending to the end of the file if it exists
       31     'b'       binary mode
       32     't'       text mode (default)
       33     '+'       open a disk file for updating (reading and writing)
       34     'U'       universal newline mode (deprecated)
       35     ========= ===============================================================
       36     
       37     The default mode is 'rt' (open for reading text). For binary random
       38     access, the mode 'w+b' opens and truncates the file to 0 bytes, while
       39     'r+b' opens the file without truncation. The 'x' mode implies 'w' and
       40     raises an `FileExistsError` if the file already exists.
       41     
       42     Python distinguishes between files opened in binary and text modes,
       43     even when the underlying operating system doesn't. Files opened in
       44     binary mode (appending 'b' to the mode argument) return contents as
       45     bytes objects without any decoding. In text mode (the default, or when
       46     't' is appended to the mode argument), the contents of the file are
       47     returned as strings, the bytes having been first decoded using a
       48     platform-dependent encoding or using the specified encoding if given.
       49     
       50     'U' mode is deprecated and will raise an exception in future versions
       51     of Python.  It has no effect in Python 3.  Use newline to control
       52     universal newlines mode.
       53     
       54     buffering is an optional integer used to set the buffering policy.
       55     Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
       56     line buffering (only usable in text mode), and an integer > 1 to indicate
       57     the size of a fixed-size chunk buffer.  When no buffering argument is
       58     given, the default buffering policy works as follows:
       59     
       60     * Binary files are buffered in fixed-size chunks; the size of the buffer
       61       is chosen using a heuristic trying to determine the underlying device's
       62       "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
       63       On many systems, the buffer will typically be 4096 or 8192 bytes long.
       64     
       65     * "Interactive" text files (files for which isatty() returns True)
       66       use line buffering.  Other text files use the policy described above
       67       for binary files.
       68     
       69     encoding is the name of the encoding used to decode or encode the
       70     file. This should only be used in text mode. The default encoding is
       71     platform dependent, but any encoding supported by Python can be
       72     passed.  See the codecs module for the list of supported encodings.
       73     
       74     errors is an optional string that specifies how encoding errors are to
       75     be handled---this argument should not be used in binary mode. Pass
       76     'strict' to raise a ValueError exception if there is an encoding error
       77     (the default of None has the same effect), or pass 'ignore' to ignore
       78     errors. (Note that ignoring encoding errors can lead to data loss.)
       79     See the documentation for codecs.register or run 'help(codecs.Codec)'
       80     for a list of the permitted encoding error strings.
       81     
       82     newline controls how universal newlines works (it only applies to text
       83     mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
       84     follows:
       85     
       86     * On input, if newline is None, universal newlines mode is
       87       enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
       88       these are translated into '\n' before being returned to the
       89       caller. If it is '', universal newline mode is enabled, but line
       90       endings are returned to the caller untranslated. If it has any of
       91       the other legal values, input lines are only terminated by the given
       92       string, and the line ending is returned to the caller untranslated.
       93     
       94     * On output, if newline is None, any '\n' characters written are
       95       translated to the system default line separator, os.linesep. If
       96       newline is '' or '\n', no translation takes place. If newline is any
       97       of the other legal values, any '\n' characters written are translated
       98       to the given string.
       99     
      100     If closefd is False, the underlying file descriptor will be kept open
      101     when the file is closed. This does not work when a file name is given
      102     and must be True in that case.
      103     
      104     A custom opener can be used by passing a callable as *opener*. The
      105     underlying file descriptor for the file object is then obtained by
      106     calling *opener* with (*file*, *flags*). *opener* must return an open
      107     file descriptor (passing os.open as *opener* results in functionality
      108     similar to passing None).
      109     
      110     open() returns a file object whose type depends on the mode, and
      111     through which the standard file operations such as reading and writing
      112     are performed. When open() is used to open a file in a text mode ('w',
      113     'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
      114     a file in a binary mode, the returned class varies: in read binary
      115     mode, it returns a BufferedReader; in write binary and append binary
      116     modes, it returns a BufferedWriter, and in read/write mode, it returns
      117     a BufferedRandom.
      118     
      119     It is also possible to use a string or bytearray as a file for both
      120     reading and writing. For strings StringIO can be used like a file
      121     opened in a text mode, and for bytes a BytesIO can be used like a file
      122     opened in a binary mode.
      View help

       實例二:

       1 import os
       2 os.getcwd()
       3 os.chdir('/home/user/project/python_model/HeadFirstPython/chapter3')
       4 man = []
       5 other = []
       6 try:
       7  data = open('sketch.txt')
       8  for each_line in data:
       9   try:
      10    (role,line_spoken) = each_line.split(':',1)
      11    line_spoken = line_spoken.strip()
      12    if role == 'Man':
      13     man.append(line_spoken)
      14    elif role == 'Other Man':
      15     other.append(line_spoken) 
      16   except ValueError:
      17    pass
      18  data.close()
      19 except IOError:
      20  print('The datafile is missing!')
      21 try:
      22  man_file = open('man_data.txt','w') # open a new file man_data.txt in-mode 'w'
      23  other_file = open('other_data.txt','w')# if the file don't exist then creat it.
      24  print(man,file=man_file)# write man data into man_file.txt
      25  print(other,file=other_file)# write other data into other_file.txt
      26  man_file.close()# close man_file
      27  other_file.close()# close other_file
      28 except IOError:
      29  print('File error')
      View Code

      注:發生異常后文件會保持打開 

            為了解決發生異常文件沒有自動關閉的問題,引入finally。

      用finally擴展try

        在實例二的最后增加:

          finally:

            man_file.close()

            other_file.close()

             在python中字符串是不可變的,因為永遠不知道還有哪些變量指向某個特定的字符串;

        盡管可以為Python變量賦數值,但實際上變量并不包含所賦的數據;

        此外,還有元組也不可以改變,即:不可改變的列表;

        所有數值類型也是不可變的。

      知道錯誤類型還不夠

        如果想知道產生錯誤的具體原因,就需要添加異常處理捕獲機制,如下:

        假設現在要打開一個文件:missing.txt,但這個文件并不存在,如下代碼:

        try:

          data=open('missing.txt')

          print(data.readline(),end='')

        except IOError:

          print('File error')

        finally:

          if 'data' in locals():

            data.close()

      繼續改進:

        except IOError as err:           #為異常對象起一個名

          print('File error: ' + str(err))  #然后作為錯誤消息的一部分

      然后運行,結果是:File error:[Errno 2] No such file or directory: 'missing.txt';

      但是如果代碼量大了,這種邏輯處理方法會很麻煩,這樣引入with。

      用with處理文件

        使用以下代碼可以替代上面的try/except/finally代碼:

        try:

         with open('its.txt',"w") as data:

          print("It's...",file=data)

        except IOError as err:

          print('File error:' + str(err))

        注:使用with時,不需要操心關閉打開文件,Python解釋器會自動處理;

          其實,with語句使用了一種名叫:上下文管理協議(context management protocol)的Python技術。

      接下來修改第二章筆記中的print_lol()函數

        在Python中,標準輸出是:sys.stdout,可以從標準庫sys模塊導入。

        實例三

      對函數print_lol做修改

      def print_lol(the_list,indent=False,level=0,fh=sys.stdout ):
        for each_item in the_list:
          if isinstance(each_item,list):
            print_lol(each_item,indent,level+1,fh)
          else:
            for tab_stop in range(level):
              print("\t" *level,end='',file=fh)
            print(each_item,file=fh)

         不知道為什么,print_lol函數在添加了第四個參數fh=sys.stdout后,用import sys及import nester后報錯

      Traceback (most recent call last):
      File "<pyshell#9>", line 1, in <module>
      import nester
      File "/home/user/project/python_model/nester/nester.py", line 1, in <module>
      def print_lol(the_list,indent=False,level=0,fh=sys.stdout ):
      NameError: name 'sys' is not defined

         上網查找也沒有解決這個問題,挺郁悶的,已經卡住兩天了,先跳過去了。。。

      定制代碼剖析

      “腌制”數據

        Python提供了一個標準庫,名為:pickle,它可以保存和加載幾乎任何Python數據對象,包括列表。

        可以把“腌制”數據存儲到磁盤,放到數據庫或者通過網絡傳輸到另一臺計算機上。

      用dump保存,用load恢復

        使用pickle很簡單,只需導入模塊:import pickle;

                     用dump()保存數據;

                     用load()恢復數據;

        注:處理“腌制數據”,唯一的要求是,必須以二進制訪問模式打開這些文件。

      如果出問題了呢?

        腌制或解除數據腌制時如果出了問題,pickle模塊會產生一個PickleError類型的異常。

        實例四:文件數據的腌制和恢復

      >>> print(man)
      ['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
      >>> try:
          man_file=open('man_data.txt','w')
          other_file=open('other_data.txt','w')
          print(man,file=man_file)
          print(other,file=other_file)
          man_file.close()
          other_file.close()
      except IOError:
          print('File error')
      
          
      >>> import pickle
      >>> try:
          with open('man_data1.txt','wb')as man_file:
              pickle.dump(man,man_file)
      except IOError as err:
          print('File error:'+str(err))
      except pickle.PickleError as perr:
          print('Pickling error:'+str(perr))
      
          
      >>> new_man=[]
      >>> try:
          with open('man_data1.txt','rb')as man_file:
              new_man = pickle.load(man_file)
      except IOError as err:
          print('File error:'+str(err))
      except pickle.PickleError as perr:
          print('Pickling error:'+str(perr))
      
          
      >>> import nester01
      >>> nester01.print_lol(new_man)
      Is this the right room for an argument?
      No you haven't!
      When?
      No you didn't!
      You didn't!
      You did not!
      Ah! (taking out his wallet and paying) Just the five minutes.
      You most certainly did not!
      Oh no you didn't!
      Oh no you didn't!
      Oh look, this isn't an argument!
      No it isn't!
      It's just contradiction!
      It IS!
      You just contradicted me!
      You DID!
      You did just then!
      (exasperated) Oh, this is futile!!
      Yes it is!
      View Code

       最后,顯示數據的第一行和最后一行:

      >>> print(new_man[0]) #顯示第一行
      Is this the right room for an argument?
      >>> print(new_man[-1]) #顯示最后一行
      Yes it is!

      總結

        使用Pickle的通用文件I/O才是上策!嘿嘿~

        讓Python去負責文件I/O的細節,這樣把關注重點放在代碼的實際作用;

        利用Python處理、保存和恢復列表中的數據,現在已經有一套可行、可靠的機制,

        本章主要用到的方法有:

                    strip():可以從字符串中去除不想要的空白符;

                      print():BIF的參數控制,將數據發送、保存到相應地址;

                    finally:最終會執行的語句;

                    except:會傳入一個異常對象并通過as賦值到一個標識符;

                    str():BIF可以用來訪問任何數據對象的串表示;

                    locals():返回當前作用域的變量集合;

                    in:操作符用于檢查成員關系;

                    +:連接兩個字符串或兩個數字相加;

                    with:自動處理已有打開文件的關閉工作,即使出現異常也會執行;

                    sys.stdout:Python中的標準輸出,需要加載sys模塊;

                    pickle模塊:高效的將Python數據對象保存到磁盤(二進制)及從磁盤恢復,包括dump()保存和load()恢復。

      -------------------------------------------The End of Fourth Chapter-------------------------------------------              

      posted @ 2017-09-22 18:12  Blog_WHP  閱讀(369)  評論(1)    收藏  舉報
      主站蜘蛛池模板: 高中女无套中出17p| 欧美18videosex性欧美黑吊| 亚洲成人动漫av在线| 国产成年女人特黄特色大片免费| 久久国产成人高清精品亚洲| 免费福利视频一区二区三区高清 | 国产成人高清亚洲综合| 亚洲伊人成无码综合网| 中文有码字幕日本第一页| 在线视频中文字幕二区| 国产一区二区三区AV在线无码观看 | 91中文字幕在线一区| 国产伦视频一区二区三区| 人妻少妇偷人无码视频| 97在线视频人妻无码| 国产精品一二三区久久狼| 东京热一区二区三区在线| 亚洲少妇人妻无码视频| 日韩亚洲精品中文字幕| 国产精品人成视频免| 综合亚洲网| 亚洲熟妇自偷自拍另类| 日韩精品 在线 国产 丝袜| 日日摸夜夜添狠狠添欧美| 国产成人啪精品午夜网站| 国产日韩综合av在线| 狠狠综合久久综合88亚洲| 亚洲国产日韩欧美一区二区三区 | 无码人妻丰满熟妇啪啪欧美| 人妻少妇精品视频专区| 亚洲人成网站在线在线观看| 好紧好爽好湿别拔出来视频男男| 在线观看中文字幕码国产| 亚洲国产午夜精品福利| 乱色老熟妇一区二区三区| 国产尤物精品自在拍视频首页| 国产99久60在线视频 | 传媒| 老熟女多次高潮露脸视频| 免费a级黄毛片| 青草视频在线观看视频| 欧美午夜精品久久久久久浪潮|