Python文件的读写
相比java而言,Python用几行代码就可以代替java十来行的代码,真的非常不错
'''
Created on 2009-9-2
@author: jiangqh
'''
# file create and write
context = '''hello world
hello china '''
f = file("hello.txt",'w')
f.write(context)
f.close()
文件创建
#use readline() read file
f = open("hello.txt")
while True:
line = f.readline()
if line:
print line
else :
break
f.close()
一行一行的读取
# read more lines
f = file("hello.txt")
lines = f.readlines()
for line in lines:
print line
多行读取
一次性全读出文件里的内容
'''
Created on 2009-9-2
@author: jiangqh
'''
f = open("hello.txt")
context = f.read()
print context
f = open("hello.txt")
context = f.read(5) #读取前五字节
print context
print f.tell() #获得当前指针的位置
context = f.read(5) #继续当前读取五位
print context
print f.tell() #获得当前指针的位置
f.close()
相关文档:
在 python的lib目录里有一个:this.py,它其实是隐藏着一首诗,源码如下:
s =
"""Gur Mra bs Clguba, ol Gvz Crgref
Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf ......
# -*- coding: utf-8 -*-
import urllib2
from BeautifulSoup import BeautifulSoup, Tag
import re
page = urllib2.urlopen("http://bj.ganji.com/piao/zz_%E5%8C%97%E4%BA%AC-%E5%8D%97%E6%98%8C/20100210/")
soup = BeautifulSoup(page)
#ss = soup.findAll('a', href=re.compile(r"^/piao/100.&qu ......
以前没有写过python脚本,于是找了一个简易的教程过了一遍于是就是干了。
这两天测试mysql archive引擎的性能,于是用python向archive表中插入10亿条数据,python大致是如下写的:
for i in range(0,100000000)
insert into ....
结果执行之后系统就死机了,求助“伟哥”,最后发现再执行脚本的时候,for in ......
为了选择一个合适的脚本语言学习,今天查了不少有关Perl,Python,Ruby,Javascript的东西,可是发现各大阵营的人都在吹捧自己喜欢的语言,不过最没有争议的应该是Javascript现阶段还不适合用来做独立开发,它的天下还是在web应用上。 我主要是想做数据挖掘算法的研究,应该会处理大量的文本。提到文本处理,相信大部分人 ......