Python读写文件
Python中文件操作可以通过open函数,这的确很像C语言中的fopen。通过open函数获取一个file object,然后调用read(),write()等方法对文件进行读写操作。
1.open
使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
2.读文件
读文本文件
input = open('data', 'r')
#第二个参数默认为r
input = open('data')
读二进制文件: 打开二进制文件要加'b'标记
input = open('data', 'rb')
读取所有内容
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
读固定字节
file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
读每行
list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,还可以直接遍历文件对象获取每行:
for line in file_object:
process line
3.写文件
写文本文件
output = open('data', 'w')
写二进制文件
output = open('data', 'wb')
追加写文件
output = open('data', 'w+')
写数据
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
写入多行
file_object.writelines(list_of_text_strings
相关文档:
http://www.cppblog.com/oosky/archive/2005/10/11/639.html
Lesson 1 准备好学习Python的环境
Python 的官方网址:
www.python.org
点击下面连接就可以直接下载了,这里只提供了Windows下的Python。
http://www.python.org/ftp/python/2.4.2/python-2.4.2.msi
linux版本的我就不说了,因为如果你能够使用linux并安装 ......
(偶尔看到,怕忘了)
仿用户打开浏览器然后点击等行为然后获取结果,以下是我使用过的方法只是依赖与ie不过firefox等应该也有相应的调用方法:
思路就是调用ie的com组件然后就是对dom的操作跟用javascript操作dom类似,示范代码如下
#天涯登陆地址
tianyalogin = "http://www.tianya.cn/"
tianya_user = "xxxxx"
......
之前学习第九章的排序小结的时候,对sort()排序方法不理解,因为括号里面带了自定义的比较函数。
后来查手册,才发现sort()里面本来就带了这样的参数。能够自定义比较方法,确实很灵活。
不仅如此,在网上查到一个博客,作者不单停留在这表面,还查究了sort()的排序算法,确实有意思。
全文抄录如下:
http://blog.done ......
1 你好
#打开新窗口,输入:
#! /usr/bin/python
# -*- coding: utf8 -*-
s1=input("Input your name:")
print("你好,%s" % s1)
'''
知识点:
* input("某字符串")函数:显示"某字符串",并等待用户输入.
......
#!/usr/bin/env python
# -*-coding:UTF-8-*-#这一句告诉python用UTF-8编码
#=========================================================================
#
# NAME: Python MySQL test
#
# AUTHOR: benyur
# DATE : 2004-12-28
#
# COMMENT: 这是一个python连接mysql的例子
#
#================ ......