python文件操作与函数初见

## python 文件操作

r    读
w   写
a   文件后面追加
b   以二进制的方式


文件操作
参数1:文件名,可以时文件的绝对路径
参数2: option "r 读 ; w 写 ;a 文件后面追加;b 以二进制的方式"

例:对文件进行读操作,,首先文件要存在,这里要存在当前目录

f = open("1.txt","r")
print(f.read())
f.close()

例:对文件进行写操作,会覆盖原来的内容.文件不存在会自动创建。

f = open("1.txt","w")
f.write("hello world!")
f.close()

\
换行符: \n

#全局变量申明
ENCODING = "utf-8"
f = open("1.txt","w",encoding=ENCODING)
f.write("hello world! \n你咋不上天呢\n no zuo no die\n尼玛的")
f.close()

文件的操作方法

**
read()              把文件的所有内容都读取出来,返回一个字符串
write(data)         把字符串data写到文件中去,只接受字符串参数
f.readline()        逐行返回文件内容
f.readlines()       返回一个list
print(f.name)       返回文件名
f.fileno()          文件描述符,类似索引号
print(f.encoding)   返回文件编码
f.tell()            返回文件的光标位置
f.truncate(size)    只有写文件才可以用,清空文件,size表示清空到什么地方.
help(f.seek)        控制文件光标,文件需要使用b方式打开**

f = open("1.txt","r",encoding=ENCODING)
print(f.readlines())
f.close()

['河舟海船\n', '往事瓦落\n', '帝王将相\n', '相见欢\n', '清平调']

函数

函数定义(声明):

以关键字def开头,函数名, 参数:回车缩进

def function(arg1, arg2, ……):
    pass

函数的就是一种封装的思想,把细小的功能或者可以缩小的功能封装成一种函数

函数的调用:

函数名直接传入参数就可以

function123

arg1, arg2   形参
123     实参
def fun(a, *args, **kwargs):
    pass

*args 代表什么意思 list

*goushi

**kwargs 代表什么意思 dict

**lese

fun(1, 2, 3, 4, 5 ,a=1, b=2)

x, y, z, = 1, 2, 3

a = 1

args = 2, 3, 4, 5 list 一一对应过来

kwars ={“a”: 1, “b”: 2} dict 一一对应过来

匿名函数:

add = lambda x, y: x+y

这两个函数是等价的

def add(x, y):
    return x+y

\
例:

def jc(n):
    if n == 0:
        return 1
    else:
        result = 1
        for i in range(1, n+1):
            result *= i
        return result

def main():
    n = 10
    count = 0
    for i in range(0, n+1):
        count += jc(i)
    print("count = {0}".format(count))




if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值