(Python )格式化輸出、文件操做、json

本節學習Python的格式化輸出,文件操做以及json的簡單用法python


1.格式化輸出json


 

將非字符串類型轉換成字符串,可使用函數:str() 或者repr() ,(這兩個函數的區別目前我還沒搞懂,求解答數據結構

>>> str([1,2,3,4])
'[1, 2, 3, 4]'
>>> repr([1,2,3,4])
'[1, 2, 3, 4]'
>>> str(10)
'10'
>>> repr(10)
'10'

可使用str.ljust() 、str.rjust()、str.center()來設置字符串的對齊方式app

>>> for x in range(1,11):
    print str(x).ljust(2),str(x*x).ljust(3),str(x*x*x).ljust(4)

    
1  1   1   
2  4   8   
3  9   27  
4  16  64  
5  25  125 
6  36  216 
7  49  343 
8  64  512 
9  81  729 
10 100 1000

咱們也可使用str.format()來設置字符串的對齊方式({}中填充^、<、>分別表明居中、左對齊、右對齊):函數

>>> for x in range(1,11):
    print "{0:<2d} {1:<3d} {2:<4d}".format(x,x*x,x*x*x)

    
1  1   1   
2  4   8   
3  9   27  
4  16  64  
5  25  125 
6  36  216 
7  49  343 
8  64  512 
9  81  729 
10 100 1000

str.format() 的其餘使用方法:學習

>>> print "his name is {},his age is {}".format('Jack',30)
his name is Jack,his age is 30
>>> print "his name is {1},his age is {0}".format(30,'Jack')
his name is Jack,his age is 30
>>> print "his name is {name},his age is {age}".format(age=30,name='Jack')
his name is Jack,his age is 30
>>> print "pi is {0:.2f}".format(3.1415926)
pi is 3.14
>>> t={'name':'Jack','age':30}
>>> print "his name is {0[name]:s},his age is {0[age]:d}".format(t)
his name is Jack,his age is 30
>>> print "his name is {name:s},his age is {age:d}".format(**t)
his name is Jack,his age is 30this

咱們還有一種格式話輸出的形式,以下所示:spa

>>> print "pi is %.2f" %(3.1415926)
pi is 3.14

 

 


2.文件操做操作系統


 

咱們有一個名爲1.txt的文件,咱們能夠經過以下語句打開它:3d

f=open("1.txt","r")     

open函數的第二個參數是可選參數,能夠選擇以下幾種模式:

r:只讀模式

w:寫模式 ,若是文件不存在,自動建立

a:追加

r+:讀寫

注意:在window操做系統下,該參數能夠是:b,表明以二進制形式打開文件,因此有了組合:rb,wb 或r+b

打開後,咱們讀取其中的所有內容:

f.read()

若是咱們想一行一行的讀取,可使用f.readline()或者f.readlines()

f.readline():每次只讀取一行

>>> f=open("1.txt","r")
>>> print f.readline()
this is first line

>>> print f.readline()
this is second line

>>> f.close()

f.readlines():讀取全部行,並保存到一個列表中

>>> f=open("1.txt","r")
>>> print f.readlines()
['this is first line\n', 'this is second line\n', 'this is third line']
>>> f.close()

 

 

注意:若是咱們使用的是讀寫模式(r+、w+ 或者a+的話),在寫入後,立刻讀取,只會讀取一個EOF

>>> f=open("1.txt","r+")
>>> f.write("this is first line")
>>> print f.read()

>>> 

出現上述狀況的緣由是當調用完f.write()函數後,指針移到了文件內容的末尾處。此時讀取的話就只會讀取到EOF,解決辦法是設置指針到文件的起始位置

>>> f=open("1.txt","r+")
>>> f.write("this is first line")
>>> f.seek(0)
>>> print f.read()
this is first line

 打開文件後,必需要記得使用f.close() 函數來關閉文件以釋放資源。 一個好的使用習慣是,使用with open('file','mode') as f的形式來打開文件,這樣在with代碼塊結束後,會自動關閉文件

>>> with open("1.txt","r+") as f:
      print f.read()

    
this is first line
>>> print f.closed
True

 


3.json 


 

咱們在讀取文件的時候,讀取到的數據類型都是string類型,可是有時候,咱們可能須要存儲一些複雜的數據類型,如:列表、字典到文件中,這時候若是咱們讀取文件的時候,返回的是字符串,咱們還必須使用list(str)將其轉換成列表或字典類型,這樣的話,使得咱們的操做變得複雜。而json正好能夠解決這個問題

咱們使用json 可使數據結構轉換成字符串表示,這被稱爲序列化,咱們也可讓字符串表示轉換成相應的數據結構,這被稱爲:反序列話

咱們可使用json.dumps(x) 來將對象x序列化成json的字符串表示形式:

>>> json.dumps([1,2,3,'abbbb'])
'[1, 2, 3, "abbbb"]'

咱們還可使用json.dump(x,f) 來將序列化的x寫入文件f中:

>>> f=open("1.txt","r+")
>>> x=json.dumps([1,2,3,'abbbb'])
>>> json.dump(x,f)
>>> f.seek(0)
>>> print f.read()
"[1, 2, 3, \"abbbb\"]"

咱們想要反序列的話,可使用x = json.load(f)

>>> x=json.load(f)
>>> print x
[1, 2, 3, "abbbb"]

 四、cPickle和Pickle

也是python的標準模塊。cPickle和pickle的功能類似,只是cPickle是用c語言編寫的。可使用它們在文件中存儲python的任何對象。以後能夠把對象完整的取出來。這被稱爲持久的存儲對象。

例子:將一個列表寫進test.txt中

import cPickle as p
import os
filePath="E:\\study\\test.txt"
testList=[1,23,"teststr"]
f=file(filePath,"w")
p.dump(testList,f)
f.close()

咱們再把這個列表從文件中取出來:

import cPickle as p
import os
filepath="E:\\study\\test.txt"
if os.path.exists(filepath):
    f=open(filepath,"r")
    print p.load(f)
    f.close()
else:
    print "file is not exist"

結果:[1, 23, 'teststr'],這樣列表就成功的取出來啦。

注意:若是將import cPickle as p 替換成import json as p,那麼最後取出對象打印出來的結果是:[1, 23,u 'teststr'],這是由於json庫把json文件load成了Unicode對象。因此要變成str對象的話須要本身encode,方法能夠這樣:

import json as p
import os
filepath="E:\\study\\test.txt"
if os.path.exists(filepath):
    f=open(filepath,"r")
    getlist= p.load(f)
    getStrList=[]
    for i in getlist:
        if type(i)==type(u'a'):
            i= i.encode("utf-8") #convert Unicode to utf-8
        getStrList.append(i)
    print getStrList
    f.close()
else:
    print "file is not exist"

 但這種方法感受效率有點慢。。。。 

相關文章
相關標籤/搜索