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

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))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容