1. 程式人生 > >Python讀書筆記006:I/O

Python讀書筆記006:I/O

設定字串格式:

1、字串插入

>>> x=1/81
>>> x
0.012345679012345678
>>> print('value: %.2f' % x)
value: 0.01
>>> print('value: %.5f' % x)
value: 0.01235

轉換說明符:

x=1/81
>>> print(x)
0.012345679012345678
>>> print('x = %f' % x)
x = 0.012346
>>> print('x = %e' % x)
x = 1.234568e-02
>>> print('x = %E' % x)
x = 1.234568E-02
>>> print('x = %d' % x)
x = 0
>>> a, b, c = 'cat', 3.14, 6
>>> s = 'There\'s %d %s older than %.2f years' % (c, a, b)
>>> s
"There's 6 cat older than 3.14 years"
>>> s = 'There\'s %d %ss older than %.2f years' % (c, a, b)
>>> s
"There's 6 cats older than 3.14 years"

2、格式字串

>>> 'My {pet} has {prob}'.format(pet='dog',prob='fleas')
'My dog has fleas'
>>> 'My {0} has {1}'.format('dog','flea')
'My dog has flea'
>>> '1/81={x}'.format(x=1/81)
'1/81=0.012345679012345678'
>>> '1/81={x:f}'.format(x=1/81)
'1/81=0.012346'
>>> '1/81={x:.3f}'.format(x=1/81)
'1/81=0.012'
>>> 'num={x:.{d}f}'.format(x=1/81,d=3)
'num=0.012'
>>> 'num={x:.3f}'.format(x=1/81)
'num=0.012'
>>> 'num={x:.{c}f}'.format(x=1/81,c=5)
'num=0.01235'
>>> 'num={x:.5f}'.format(x=1/81)
'num=0.01235'

檢查檔案和資料夾

獲悉當前工作目錄中的檔案和資料夾:

>>> import os
>>> os.listdir(os.getcwd())
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python36.dll', 'pythonw.exe', 'Scripts', 'tcl', 'test.png', 'Tools', 'vcruntime140.dll']

處理文字檔案

逐行讀取文字檔案:

def print_file(fname):
    f=open(fname,'r')
    for line in f:
        print(line,end='')
    f.close()
>>> print_file('e:\\Python\\data.txt')
apple
banana
car
pear
Tencent Technology Company Limited
def print_file(fname):
    f=open(fname,'r')
    for line in f:
        print(line)
    f.close()
>>> print_file('e:\\Python\\data.txt')
apple

banana

car

pear

Tencent Technology Company Limited

因為檔案中各行都是以\n結尾的。

將整個文字檔案作為一個字串進行讀取:

def print_file2(fname):
    f=open(fname,'r')
    print(f.read())
    f.close()
>>> print_file2('e:/Python/data.txt')
apple
banana
car
pear
Tencent Technology Company Limited
>>> fname='e:/Python/data.txt'
>>> print(open(fname,'r').read())
apple
banana
car
pear
Tencent Technology Company Limited

寫入文字檔案:

def make_story1():
    f=open('story.txt','w')
    f.write('Mary had a little lamb,\n')
    f.write('and then she had some more.\n')
import os

def make_story2():
    if os.path.isfile('story.txt'):
        print('story.txt already exists')
    else:
        f=open('story.txt','w')
        f.write('Mary had a little lamb,\n')
        f.write('and then she had some more.\n')
>>> make_story2()
story.txt already exists

附加到文字檔案末尾:

def add_to_story(line,fname='story.txt'):
    f=open(fname,'a')
    f.write(line)
>>> add_to_story('\nthis is append')

將字串插入到檔案開頭:

def insert_title(title,fname='story.txt'):
    f=open(fname,'r+')
    temp=f.read()
    temp=title+'\n\n'+temp
    f.seek(0) # 讓檔案指標指向檔案開頭
    f.write(temp)

處理二進位制檔案:

def is_gif(fname):
    f=open(fname,'br')
    first4=tuple(f.read(4))
    return first4==(0x47,0x49,0x46,0x38)
>>> is_gif('e:/Python/timg.jpg')
False

讀取網頁:(urllib模組)

>>> import urllib.request
>>> page=urllib.request.urlopen('http://www.python.org')
>>> html=page.read()
>>> html[:25]
b'<!doctype html>\n<!--[if l'

(webbrowser模組)

>>> import webbrowser
>>> webbrowser.open('http://www.baidu.com')
True