案例:读取、复制、保存文件

import os               #从标准库导入os
import pickle           #保存和加载几乎任何python数据对象

def printlist(isinstance_list,indent=False,level=0,flag=sys.stdout):
   
    #isinstance_list指向参数:可以指向任何python列表,也可以是包含嵌套列表的列表;
    #indent缩进功能参数:由用户控制缩进功能是否开启
    #level缩进控制参数:由用户控制每层嵌套列表Tab个数,缺省为0
    #flag数据写入位置参数:用于标识数据写入的文件位置,缺省值sys.stdout,为print写入的默认位置,通常为屏幕所指定的列表中的每个数据项都会顺序显示在屏幕上,各数据项各占一行

    for each_item in isinstance_list:
        if isinstance(each_item,list):
            printlist(each_item,indent,level+1,flag)
        else:
            if indent:
                ''' for循环可以替代为print("\t"*level,end=' ') '''
                for tab_stop in range(level):
                    print("\t",end='',file = flag)        #end=''作为print()BIF的一个参数会关闭其默认行为,即在输入中自动包含换行
            print(each_item,file = flag)


os.chdir('C:\\Users\\Sonia\\Desktop\\')  #切换文件目录
Os.chdir('../')    #文件目录后退一格
Os.chdir('./Desktop')     #进入现目录下的desktop文件夹

man = []
other = []
new_man = []
new_other = []

try:
    data=open('sketch.txt')              #打开文件:清除式写模式(w),追加式写模式(a),不清除式写和读(w+),只读(r)   


    data.seek(0)                              #返回文件起始位置,也可以使用tell()

    #按行读取整个文件
    for each_line in data:                    #使用for循环读取文件
        print(each_line,end='')               #readline从文件中获取一个数据行


    #按照冒号将一句话split,并且插入said,使用if语句排除split无冒号行的报错
    for each_line in data:
        if not each_line.find(':') == -1:                     #find函数用于在字符串内查找特定值,找不到返回-1,找到返回该值所在位置
            (role,line_spoken)=each_line.split(":",1)         #参数1表示只识别第一个冒号
            print(role,end='')
            print(' said:',end='')
            print(line_spoken,end='')
        else:
            print(each_line,end='')
            

    #按照冒号将一句话split,并且插入said,使用try语句排除split无冒号行的报错
    for each_line in data:
    try:
        (role,line_spoken)=each_line.split(":",1)
        print(role,end='')
        print(' said:',end='')
        print(line_spoken,end='')
    except ValueError:
        #print(each_line,end='')
        pass                 #使用pass继续执行代码,即为空语句或null语句
        

    #按照冒号将一句话split,并且插入said,使用try语句排除split无冒号行的报错'''
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(":",1)
            line_spoken = line_spoken.strip()     #strip从字符串中去除空白符
            if role == 'Man':
                man.append(line_spoken)
            elif role == 'Other Man':
                other.append(line_spoken)
        except ValueError:
            pass  

    data.close()             #关闭文件

except IOError:
    print('The data file is missing!')
    

#使用try+except+finally实现文件的打开、写入、关闭
try:
    man_data = open('man_data.txt',"w")
    other_data = open('other_data.txt',"w")

    print(man,file = man_data)  
    print(other,file = other_data)
    #print('Norwegian Blues stun easily.',file = data)         #print(写至文件的内容,所写数据文件对象的名)

except IOError as err:                                         #将异常对象命名
    print('File Error:' + str(err))                            #使用str将异常对象转换(或强制转换)为字符串,作为错误消息的一部分

finally:
    if 'man_data' in locals():                                 #locals返回当前作用域中定义的所有名的一个集合,如果找到则文件成功打开
        man_data.close()        
    if 'other_data' in locals():
        other_data.close()


#使用try+with+except实现文件的打开、写入、关闭
try:
    with open('man_data.txt',"w") as man_data:
        printlist(man,flag = man_data)
        
    with open('other_data.txt',"w") as other_data:
        printlist(other,flag = other_data)

    with  open('man_data2.txt',"w") as man_data2,open('other_data2.txt',"w") as other_data2:
        print(man,file = man_data2)
        print(other,file = other_data2)
        
except IOError as err:
    print('File Error:' + str(err))                  #使用str将异常对象转换(或强制转换)为字符串



#使用try+with+pickle实现文件的打开、写入、关闭、读取
try:
    with open('pickle_man_data.txt',"wb") as man_file,open('pickle_other_data.txt',"wb") as other_file:
        pickle.dump(man,man_file)
        pickle.dump(other,other_file)
        
    with open('pickle_man_data.txt',"rb") as man_file,open('pickle_other_data.txt',"rb") as other_file:
       new_man = pickle.load(man_file)
       new_other = pickle.load(other_file)
              
except IOError as err:
    print('File Error:' + str(err))                  #使用str将异常对象转换(或强制转换)为字符串

except pickle.PickleError as perr:
     print('Pickling Error:' + str(perr))
1、实验描述 本案例主要是通过字节流的读写,实现图片文件复制。 2、推荐步骤 2-1. 新建项目工程,工程名为CORE_C09_049: 2-1.1. 复制一个图片文件到当前项目工程的根目录下,命名为icon.png 2-1.2. 新建java类-CopyDemo01。 2-2. 创建复制图片文件的方法-copyImageFile: 2-2.1. 第一个入参是:需要复制的图片文件路径 2-2.2. 第二个入参是:复制后图片文件保存路径 2-2.3. 无返回值 2-3. copyImageFile方法中实现图片文件复制: 2-3.1. 通过第一个入参,获取FileInputStream对象; 2-3.2. 通过第二个入参,获取FileOutputStream对象; 2-3.3. 创建byte[]变量,长度为2048,用于存放读取到的数据 2-3.4. 通过FileInputStream的read方法读取数据并保存到byte数组中 1) 把read方法的返回值赋值给int变量len。(返回值为read方法读取到的字节数) 2-3.5. 通过while循环,读取复制图片数据并写入复制图片中: 1) 循环条件:读取到的数据长度不等于-1,即表示读取到有效数据; 2) 循环内容:通过FileOutputStream的write方法将读取到的缓存数据写入图片文件; 2-4. 循环结束后,关闭文件资源: 2-4.1. 关闭输出流资源:FileOutputStream。 2-4.2. 关闭输入流资源:FileInputStream。 2-5. 抓取上述代码中抛出的FileNotFoundException和IOException。 3、验证与测试 3-1. 程序测试: 3-1.1. 创建程序入口函数-main 3-1.2. 调用copyImageFile方法,把当前项目工程下的图片文件icon.png复制到当前工程目录下 1) 原文件路径:icon.png 2) 目标文件路径:copyIcon.png 3-1.3. 运行该项目,观察能否能够实现图片的复制
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值