文件处理&函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件处理&函数相关的知识,希望对你有一定的参考价值。

一.文件处理

1.介绍

    计算机系统:计算机硬件,操作系统,应用程序

    应用程序无法直接操作硬件,通过操作系统来操作文件,进而读/写硬件中的文件。

    python打开文件过程:

#打开
f=open(a.txt,r)
#通过句柄对文件进行操作
read_f=f.read()
#关闭文件
f.close()
with open(‘a.txt‘,‘r‘) as f: #不需要关闭
f.close() #回收操作系统打开的文件
del f #回收应用程序级的变量

2.打开文件的模式

    a.打开文本文件

#r,只读模式【默认模式,文件必须存在,不存在则抛出异常】
f=open(a.txt,encoding=utf-8)
data1=f.read()
print(f.readline(),end=‘‘)
print(f.readlines())
#w,只写模式【不可读;不存在则创建;存在则清空内容】
f=open(a.txt,w,encoding=utf-8)
f.write(werf)
#a,只追加写模式【不可读;不存在则创建;存在则只追加内容】
f=open(a.txt,a,encoding=utf-8)
f.write(werf\n)

    b.对于非文本文件,只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式

with open(1.jpg,rb) as f_read:
    data=f_read.read()
    print(data)
with open(a.txt,rb) as f_read:
    data=f_read.read().decode(utf-8) #解码
    print(data)
with open(a.txt,wb)as f_write:
    f_write.write(adsf.encode(utf-8))
‘‘‘
练习,利用b模式,编写一个cp工具,要求如下:

  1. 既可以拷贝文本又可以拷贝视频,图片等文件

  2. 用户一旦参数错误,打印命令的正确使用方法,如usage: cp source_file target_file
‘‘‘
import sys
if len(sys.argv)!=3:
    print(usage:cp source_file target_file)
    sys.exit()
source_file,target_file=sys.argv[1],sys.argv[2]
print()
with open(source_file,rb)as f_read,open(target_file,wb)as f_write:
    for line in f_read:
        f_write.write(line)

3.文件内光标的移动

#以文本模式读文件,n代表的是字符的个数
with open(a.txt,r)as f_read:
    data=f_read.read(6)
    print(data)
#以b模式读文件,n代表的是字节的个数
with open(a.txt,rb)as f_read:
    data=f_read.read(6)
    print(data)
# tell:告诉当前光标的位置
with open(a.txt,r,encoding=utf-8)as f_read:
    data=f_read.read(4)
    data1=f_read.tell()
    print(data,data1)
# seek:移动光标(0:文件开头默认;1:文件当前光标;2:文件末尾)
with open(a.txt, r, encoding=utf-8)as f_read:
    data = f_read.seek(3)
    data1 = f_read.read()
    print(data, data1)

 

# 实现tail功能
import time
with open(access.log, rb)as f_read:
    f_read.seek(0,2)
    while True:
        line = f_read.readline()
        if line:
            print(line.decode(utf-8),end=‘‘)
        else:
            time.sleep(1)

    4.文件的修改

   

import os

with open(a.txt) as read_f,open(.a.txt.swap,w) as write_f:
    for line in read_f:
        line=line.replace(alex,SB)
        write_f.write(line)

os.remove(a.txt)
os.rename(.a.txt.swap,a.txt)

二.函数

    1.函数分类

    a.内置函数:为了方便我们的开发,针对一些简单的功能,python解释器已经为我们定义好了的函数即内置函数。对于内置函数,我们可以拿来就用而无需事先定义,如len(),sum(),max()

     b.自定义函数:很明显内置函数所能提供的功能是有限的,这就需要我们自己根据需求,事先定制好我们自己的函数来实现某种功能,以后,在遇到应用场景时,调用自定义的函数即可。

    2.定义函数

#语法
def 函数名(参数1,参数2,参数3,...):
    ‘‘‘注释‘‘‘
    函数体
    return 返回的值
#1、无参:应用场景仅仅只是执行一些操作,比如与用户交互,打印
#2、有参:需要根据外部传进来的参数,才能执行相应的逻辑,比如统计长度,求最大值最小值
#3、空函数:设计代码结构
3.调用函数
1 语句形式:foo()
2 表达式形式:3*len(‘hello‘)
3 当中另外一个函数的参数:range(len(‘hello‘))
函数练习:
‘‘‘
1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
‘‘‘
import os
def foo(x,y,z):
    ‘‘‘

    :param x: 文件名
    :param y: 修改的内容
    :return:
    ‘‘‘
    with open(x,r)as f_read,open(tmp.txt,w)as f_write:
        for line in f_read:
            data=line.replace(y,z)
            f_write.write(data)
    os.remove(x)
    os.rename(tmp.txt,x)
foo(a.txt,ha,yi)
‘‘‘
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
‘‘‘
def foo(a):
    n_num=0
    n_word=0
    n_space=0
    n_other=0
    for word in a:
        if word.isdigit():n_num+=1
        elif word.isalpha():n_word+=1
        elif word== :n_space+=1
        else:n_other+=1
        print(word)
    print(n_num,n_word,n_space,n_other)
foo(123   wef   wd23!2)
‘‘‘
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
‘‘‘
def func(a):
    if len(a)>5:return True
    else:return False
print(func(23rsdsd2))
‘‘‘
4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
‘‘‘
def func(a):
    while True:
        if type(a)!=list:
            print(list please!)
        else:break
    if len(a)>=2:
        data=a[0:2]
    else:data=a
    print(data)
func([12,])
‘‘‘
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
‘‘‘
def func(a):
    l=[]
    for x in a:
        if a.index(x)%2!=0:
            l.append(x)
    return l
print(func([qef,123,asdf,dcsc,csdcd]))
‘‘‘
6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
‘‘‘
def func(dic):
    for key in dic:
        if len(dic[key])>=2:
            new_value=dic[key][0:2]
            dic.pop(key)

            dic[key]=new_value
    return dic
print(func( {"k1": "v1v1", "k2": [11,22,33,44]}))

    3.函数对象

#1 可以被引用
#2 可以当作参数传递
#3 返回值可以是函数
#3 可以当作容器类型的元素

    4.函数嵌套

def max1(x,y):
    return x if x>y else y
def max4(a,b,c,d):
    res1=max1(a,b)
    res2=max1(c,d)
    res=max1(res1,res2)
    return res
print(max4(1,2,3,4))
# 函数的嵌套定义
def f1():
    def f2():
        def f3():
            print(from f3)
        f3()
    f2()
f1()

    4.名称空间和作用域

名称空间:存放名字的地方。局部名称空间,全局名称空间,内置名称空间

名字的查找顺序:局部名称空间--->全局名称空间-->内置名称空间


 

 

 

 

 

 

 

 

 

 

 

    

    

以上是关于文件处理&函数的主要内容,如果未能解决你的问题,请参考以下文章

CSP核心代码片段记录

有没有办法将2个非常相似的代码片段组合成一个函数并重复?

VSCode自定义代码片段——声明函数

VSCode自定义代码片段8——声明函数

在 Python 多处理进程中运行较慢的 OpenCV 代码片段

组件&Props