python文件及函數初步

#-*- encoding: utf-8 -*-
'''
Created on 2013-*-*

@author: ****
'''
f=open("b.txt")
#去掉換行符
data =[line.strip() for line in f]
print data
f.close()
print f.closed
#以下是文件的內部屬性
#file.closed True 表示文件已經被關閉, 否則爲 False 
#file.encoding
#a文件所使用的編碼 - 當 Unicode 字符串被寫入數據時, 它們將自動使
#用 file.encoding 轉換爲字節字符串; 若 file.encoding 爲 None 時使
#用系統默認編碼 
#file.mode 文件打開時使用的訪問模式 
#file.name 文件名 
#file.newlines
#a未讀取到行分隔符時爲 None , 只有一種行分隔符時爲一個字符串, 當
#文件有多種類型的行結束符時,則爲一個包含所有當前所遇到的行結束
#符的列表 
#file.softspace 爲 0 表示在輸出一數據後,要加上一個空格符,1 表示不加。這個屬
#write file
import os
#filename=raw_input("enter file name\n")

#fp=open(filename,"w")
#while True:
#    line = raw_input("enter lines(. to stop)")
#    if line !=".":
#    	fp.write("%s%s" % (line,os.linesep))
#        print fp.tell()
#    else:
#         break
#fp.close()        
        
import sys
print len(sys.argv)
print sys.argv[0]

for tempdir in("/tcl","c:\\"):
    if os.path.isdir(tempdir):
        print "tempdir =%s " % tempdir
        print"current dir:%s" % os.getcwd()      
        break
    else:
        print "no dir"
if tempdir :
    os.chdir(tempdir)
    print"current dir: %s" % tempdir   
    print"current dir:%s" % os.getcwd()    
#create a didr,不能創造重複的文件
#os.mkdir("example dir")
#os.chdir("example dir")
print"current dir:%s" % os.getcwd()       

print os.listdir("c:\\tcl")

#join 連接
path= os.path.join(os.getcwd(),"a.txt") #path =C:\tcl\a.txt 
print "path =%s " % path
print os.path.isfile(path)
print os.path.isdir(path)

print os.path.split(path) #('C:\\tcl', 'a.txt')
print os.path.splitext(path) #('C:\\tcl\\a', '.txt')

os.chdir("C:\Users\wangkjun\workspace\pythonstudy")
print os.getcwd()

#格式化存儲
import pickle
f = open("pick.dat","w")
pickle.dump(123, f)
pickle.dump("456", f)
pickle.dump(("this","is","test"), f)
pickle.dump([1,2,3], f)
f.close

f=open("pick.dat","r")
text = pickle.load(f)        
print text,type(text) #123 <type 'int'>
text = pickle.load(f)        
print text,type(text) #456 <type 'str'>
text = pickle.load(f)
print text, type(text)
text = pickle.load(f)
print text, type(text)
 
#異常
#print 1/0      
alist=[]
#print alist[0]#IndexError: list index out of range

try:
    f-open("aa.txt","r")
except Exception, e:
    print "can't Open file %s"  % e   
finally:
    print "finally"    
    
#斷言
assert 1==1   
#assert 1!=1   #AssertionError

try:
    float("abc123")
except Exception, e:
    import sys
    print sys.exc_info()
finally:
    pass        


from random import choice,randint

nums = [randint(1,10) for i in range(2)]
nums.sort(reverse=True)
print nums

def f1():
    def f2():
        print "f2"
    print "f1"
 
print f1()

def foo():
    print "foo"
foo.__doc__="this is test"
foo.__version__=1.0
#函數賦值
foo1=foo
print foo1()

help(foo1) #Help on function foo in module __main__:
print foo1.__doc__,foo1.__version__ #this is test 1.0

def hand_f(f):
    f()

def hello():
    print "hello world"
#函數直接作爲參數
print hand_f(hello)

#內置函數作爲參數
def convert(fun,seq):
    return [fun(ele) for ele in seq]

seq1=[10.4,56.7,41,"78"]
print convert(int,seq1)
    
    
def testit(func,*nkwargs,**kwargs):
    try:
        ret=func(*nkwargs,**kwargs)
        result=(True,ret)
    except Exception,diag:
        result=(False,str(diag))
    return result

def test():
    funcs=(int,long,float)
    vals=(1234,12.34,"1234","12.34")
    for eachfunc in funcs:
        print "-"*20
        for eachvalue in vals:
            retval=testit(eachfunc,eachvalue)
            if retval[0]:
                print("%s(%s) =") % (eachfunc.__name__,eachvalue),retval[1]
            else:
                 print("failed %s(%s) =") % (eachfunc.__name__,eachvalue),retval[1]  

test()                    







#outout
['thisistest', 'I love Python!', 'Hello, world', 'Good Bye!']
True
1
C:\Users\wangkjun\workspace\pythonstudy\python_file_425.py
tempdir =/tcl 
current dir:C:\Users\wangkjun\workspace\pythonstudy
current dir: /tcl
current dir:C:\tcl
current dir:C:\tcl
['bin', 'demos', 'doc', 'example dir', 'include', 'lib', 'license-at8.5-thread.terms', 'licenses', 'MANIFEST_at8.5.txt', 'README-8.5-thread.txt', 'test']
path =C:\tcl\a.txt 
False
False
('C:\\tcl', 'a.txt')
('C:\\tcl\\a', '.txt')
C:\Users\wangkjun\workspace\pythonstudy
123 <type 'int'>
456 <type 'str'>
('this', 'is', 'test') <type 'tuple'>
[1, 2, 3] <type 'list'>
can't Open file [Errno 2] No such file or directory: 'aa.txt'
finally
(<type 'exceptions.ValueError'>, ValueError('could not convert string to float: abc123',), <traceback object at 0x01846800>)
[6, 2]
f1
None
foo
None
Help on function foo in module __main__:


foo()
    this is test


this is test 1.0
hello world
None
[10, 56, 41, 78]
--------------------
int(1234) = 1234
int(12.34) = 12
int(1234) = 1234
failed int(12.34) = invalid literal for int() with base 10: '12.34'
--------------------
long(1234) = 1234
long(12.34) = 12
long(1234) = 1234
failed long(12.34) = invalid literal for long() with base 10: '12.34'
--------------------
float(1234) = 1234.0
float(12.34) = 12.34
float(1234) = 1234.0
float(12.34) = 12.34




    
        
        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章