Python Cookbook学习记录 ch2_1_2013/10/27

开始第二章的学习,第二章讲的是python对文件的操作

2.1读取文件

既然是文件操作,那么就必须先有文件,在如下目录“E:\PythonCookbook\CHA2”创建文件后,在交互模式下发现python无法直接读取文件,文件木有找到

>>> all_the_text = open('thefile.txt').read()

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    all_the_text = open('thefile.txt').read()
IOError: [Errno 2] No such file or directory: 'thefile.txt'

原因是此文件并不在当前python的工作目录下,可以使用os.getcwd()来获取当前目录:

>>> os.getcwd()
'C:\\Python27'

可见当前目录还是C盘的安装目录,这时候需要将目录切换到我想要的目录,可以通过“os.chdir”来实现:

>>> os.chdir('E:\PythonCookbook\CHA2')
>>> all_the_text = open('thefile.txt').read()
>>> print all_the_text
A "Hello World" program has become the traditional first program that many people learn. In general, it is simple enough so that people who have no experience ............

a.一次性读取所有内容并放置到一个大字符串中:

all_the_text = open('thefile.txt').read()    # all text from a text file
all_the_data = open('abinfile', 'rb').read() # all data from a binary file

b.逐行读取文本文件内容,并将读取到的数据放置在一个字符串列表中:

>>> file_object.close()
>>> file_object = open('thefile.txt')
>>> list_of_all_the_lines = file_object.readlines()
>>> for item in list_of_all_the_lines:
        print item

c.但是上述方法读出的每行文本末尾都有"\n"符号,如果不希望这样,可以使用如下方法:

>>> file_object.close()
>>> file_object = open('thefile.txt')
>>> list_of_all_the_lines = file_object.readlines()
>>> for item in list_of_all_the_lines:
    item = item.rstrip()
    print item

d.读取二进制文件一定字节

>>> file_object.close()
>>> file_object = open('abinfile','rb')
>>> chunk = file_object.read(5)
>>> print chunk
01011

e.逐行读取文本进行处理:

file_object = open('thefile.txt', 'rU'):
try:
    for line in file_object:
        do_something_with(line)
finally:
    file_object.close()

 

posted on 2013-10-27 16:52  七海之风  阅读(170)  评论(0)    收藏  举报

导航