1. 程式人生 > >讀書筆記--《Python基礎教程第二版》--第十一章 文件和素材

讀書筆記--《Python基礎教程第二版》--第十一章 文件和素材

ja

第十一章 文件和素材


11.1 打開文件

open函數用來打開文件,語法如下:

open(name[,mode[,buffering]])

f = open(r‘/home/python/somefile.txt‘)


11.1.1 文件模式

r 讀模式

w 寫模式

a 追加模式

b 二進制模式(可添加到其他的模式中)

+ 讀寫模式(可添加到其他的模式中)



在模式參數中使用U參數能夠在打開文件時使用通用的換行符支持模式


11.1.2 緩沖

單位是字節,使用flush或者close時更新到磁盤



11.2 基本文件方法

sys.stdin

sys.stdout

sys.stderr 在文件對象中也可以使用


11.2.1 讀和寫

>>> f=open(‘somefile.txt‘,‘w‘)
>>> f.write(‘Hello,‘)
>>> f.write(‘World!‘)
>>> f.close()

>>> f=open(‘somefile.txt‘,‘r‘)
>>> f.read(4)
‘Hell‘
>>> f.read()
‘o,World!‘



11.2.2 管式輸出

# cat somescript.py 
#!/usr/bin/env python
#coding=utf-8
# somescript.py
import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print ‘Wordcount:‘, wordcount


# cat somefile.txt 
Your mother was a hamster and your
father smelled of elderberries.


# cat somefile.txt |python somescript.py 
Wordcount: 11



seek(offset[,whence])

tell方法返回當前文件的位置



11.2.3 讀寫行

file.readline 讀取單獨的一行

file.readline(5)

file.readlines

file.writelines 讀取文件中所有的行並作為列表返回

file.write

沒有writeline方法


11.2.4 關閉文件

try:
  #write data to your file
fianlly:
  file.close()
file.fush()
with open("somefile.txt") as somefile:
   do_someting(somefile)


11.2.5 使用基本文件方法

cat somefile.txt
Welcome to this file
There is nothing here except
This stupid haiku
>>> f=open(‘/home/mysql/somefile.txt‘)
>>> f.read(7)
‘Welcome‘
>>> f.read(4)
‘ to ‘
>>> f.close()
>>> f=open(‘/home/mysql/somefile.txt‘)
>>> 

>>> print f.read()
Welcome to this file
There is nothing here except
This stupid haiku
>>> f.close()

>>> f=open(‘/home/mysql/somefile.txt‘)
>>> for i in range(3):
...   print str(i)+":"+f.readline()
... 
0:Welcome to this file
1:There is nothing here except
2:This stupid haiku
>> f.close()


>>> import pprint
>>> pprint.pprint(open(‘/home/mysql/somefile.txt‘).readlines())
[‘Welcome to this file\n‘,
 ‘There is nothing here except\n‘,
 ‘This stupid haiku\n‘]

$ cat somefile.txt 
this
is no
haiku

>>> f=open(r‘/home/mysql/somefile.txt‘)
>>> line=f.readlines()
>>> f.close()
>>> line[1]="isn‘t a \n"
>>> f=open(r‘/home/mysql/somefile.txt‘,‘w‘)
>>> f.writelines(line)
>>> f.close()

$ cat somefile.txt 
this
isn‘t a 
haiku


11.3 對文件內容進行叠代

def process(string):
    print ‘Processing:‘,string


11.3.1 按字節處理

用read方法對每個字符進行循環

f = open(filename)
char = f.read(1)
while char:
    process(char)
    char = f.read(1)
f.close()


f = open(filename)
while True:
    char = f.read(1)
    if not char: break
    process(char)
f.close()


11.3.2 按行操作

f = open(filename)
while True:
    line = f.readline()
    if not line: break
    process(line)
f.close()


11.3.3 讀取所有內容

如果文件不是很大,可以一次性讀取

f = open(filename)
for char in f.read():
    process(char)
f.close()


f = open(filename)
for line in f.readlines():
    process(line)
f.close()


11.3.4 使用fileinput實現懶惰行叠代

fileinput 模塊包含了打開文件的函數


import fileinput
for line in fileinput.input(filename):
    process(line)

11.3.5 文件叠代器

f = open(filename)
for line in f:
    process(line)
f.close()
for line in open(filename):
    process(line)

import sys
for line in sys.stdin:
  process(line)

可以對文件叠代器執行和普通叠代器相同的操作,list(open(filename))

>>> f=open(r‘/home/mysql/somefile.txt‘,‘w‘)
>>> f.write(‘Fist line\n‘)
>>> f.write(‘Second line\n‘)
>>> f.write(‘Third line\n‘)
>>> f.close()
>>> lines=list(open(‘somefile.txt‘))

>>> lines
[‘Fist line\n‘, ‘Second line\n‘, ‘Third line\n‘]

>>> first,second,third=open(‘somefile.txt‘)
>>> first
‘Fist line\n‘
>>> second
‘Second line\n‘
>>> third
‘Third line\n‘




本文出自 “小魚的博客” 博客,謝絕轉載!

讀書筆記--《Python基礎教程第二版》--第十一章 文件和素材