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')
¶Á¶þ½øÖÆÎļþ
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)
×¢Ò⣬µ÷ÓÃwritelinesдÈë¶à
Ïà¹ØÎĵµ£º
8.PythonÖÐûÓÐswitchÓï¾ä,¿ÉÒÔÓÃif..elif..elseÓï¾äÍê³ÉͬÑùµÄ¹¤×÷(ijЩ³¡ºÏ,ʹÓÃ×Öµä»á¸ü¼Ó¿ì½Ý)
9.whileÓï¾ä°üº¬Ò»¸öelseµÄ´Ó¾ä.
10.rangeÏòÉÏÑÓÉìµ½µÚ¶þ¸öÊý,¼´Ëü²»°üº¬µÚ¶þ¸öÊý.
11.ʹÓÃglobalÓï¾ä¿ÉÒÔÇå³þµØ±íÃ÷±äÁ¿ÊÇÔÚÍâÃæµÄ¿é¶¨ÒåµÄ. ......
1.1. Óï·¨
1.1.1. if
>>> x=int(raw_input("please enter an integer:"))
please enter an integer:-8
>>> if x<0:
... print 'negative'
... elif x==0:
... print 'zero'
... else:
... print 'positive'
...
negative
ÕâÀïÓм¸¸ö֪ʶµãÐèÒªÌáÐÑ£º
1¡£ºÍ ......
Èç¹ûpythonµ÷ÓÃÍⲿ³ÌÐò£¬ÐèÒªÖ±½ÓץȥÃüÁîÐеÄÊä³ö£¬ÓÐʲôºÃµÄ°ì·¨ÄØ£¿
ÕâÀïÎÒÃÇÐèÒªÓõ½ os.popen Õâ¸ö¹ÜµÀ£¬È»ºóÓà read¡¢readline»òÕßreadlinesÀ´¶ÁÈ¡ÃüÁîÐÐÊä³ö
#ÐèÒªÖ´ÐеÄÃüÁî
strCommand = 'xxxxxxxxxxxxxxxxx'
#ÓÃpopenÀ´Ö´ÐÐÃüÁîÐÐ
oStdout = os.popen(strCommand)
#¼ÙÉèÊä³öµÄÄÚÈÝÖ»ÓÐÒ»ÐÐ
strStdout = ......
PythonÊÇĿǰ¹ã·ºÊ¹ÓõÄÒ»ÃŶ¯Ì¬ÓïÑÔ£¬ÀàËÆJava£¬Ô´´úÂë±ØÐëÊ×ÏÈÓɱàÒëÆ÷ת»»³É×Ö½ÚÂ루byte code£©£¬È»ºóÔÙÓɽâÊÍÆ÷À´Ö´ÐÐ×Ö½ÚÂë¡£ÓëJava²»Í¬µÄÊÇ£¬PythonµÄ±àÒëÆ÷ºÍ½âÊÍÆ÷¶¼ÊÇÒ»¸ö³ÌÐò¡£Òò´Ë£¬Ô´´úÂëÒ²¿ÉÒÔÖ±½Ó½»¸øÕâ¸ö±àÒëÆ÷£¯½âÊÍÆ÷À´Ö´ÐС£
ʹÓÃPython±àд³ÌÐò£¬Äã²»ÐèÒªÔ¤ÏÈÉùÃ÷ºÃ±äÁ¿µÄÀàÐÍ£¬ÒòΪPythonÖбäÁ¿µÄÀ ......
# -*- 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 ......