Chinaunix首页 | 论坛 | 博客
  • 博客访问: 835320
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2010-11-18 15:42:55

简明 Python 教程 / 输入/输出 / 文件

你可以通过创建一个file类的对象来打开一个文件,分别使用file类的readreadlinewrite方法来恰当地读写文件。对文件的读写能力依赖于你在打开文件时指定的模式。最后,当你完成对文件的操作的时候,你调用close方法来告诉Python我们完成了对文件的使用。

#!/usr/bin/python
# Filename: using_file.py


poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
'''


f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()

    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file

(源文件:)

输出

$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!

它如何工作

首先,我们通过指明我们希望打开的文件和模式来创建一个file类的实例。模式可以为读模式('r')、写模式('w')或追加模式('a')。事实上还有多得多的模式可以使用,你可以使用help(file)来了解它们的详情。

我们首先用写模式打开文件,然后使用file类的write方法来写文件,最后我们用close关闭这个文件。

接下来,我们再一次打开同一个文件来读文件。如果我们没有指定模式,读模式会作为默认的模式。在一个循环中,我们使用readline方法读文件的每一行。这个方法返回包括行末换行符的一个完整行。所以,当一个 空的 字符串被返回的时候,即表示文件末已经到达了,于是我们停止循环。

注意,因为从文件读到的内容已经以换行符结尾,所以我们在print语句上使用逗号来消除自动换行。最后,我们用close关闭这个文件。

现在,来看一下poem.txt文件的内容来验证程序确实工作正常了。


阅读(1110) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-11-19 15:36:59

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com