python文件及函数初步

本文详细介绍了使用Python进行文件操作、文件属性查看、文件创建、文件路径操作、数据持久化存储(pickle)、异常处理、断言、函数定义、函数参数传递、函数赋值及调用等核心编程技巧。涵盖了从基本的文件读写到高级的文件系统操作,以及数据的序列化和反序列化过程,还涉及到Python中的一些内置函数和模块的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#-*- 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




    
        
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值