【p3】·python文件读取·数据存储(pigeon详细说)

继续记录书本《head first python》第三章及后面的知识,真是越到后面越兴奋,越难越清晰。

   首先拿来测试的文件(包括后面用到的文件)如何下载:http://python.itcarlow.ie/(百度搜索关键字:head first python就能找到该支持网站),登录该网页可以看到以下页面




  【点击功能栏【Resources】,就能进入以下资源页面】


【对应点击黄色文件名字(如sketch.txt,coach kelly's data中需要的资料TXT files),就会自动弹窗出现下载窗口。课本中有提及的文件都可以在这里下载】


接下来开始数据游戏了,gogogogo关于【sketch.txt数据处理】

【sketch.txt】部分文件内容如下,操作将使数据更易于浏览查阅

                                 

Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!

【1】新建一个文件夹,将sketch.txt复制到文件夹中,在文件夹中再新建一个py后缀文件用于编辑(如下)

data=open('sketch.txt')
for each_line in data:
    try:
        (role,each_spoken)=each_line.split(':',1)
        print(role,end='')
        print('said:',end='')
        print(each_spoken,end='')
    except:
        pass
data.close()

           (1.1) 使用open要在数据文件所在的地方才可以,所以要记得把sketch.txt跟py文件放一起,不然会报异常,找不到文件。【运行只要出现unexpected indent错误弹窗,就是你代码缩进有问题,检查下空格多或少,是否对齐】

<pre name="code" class="python"><span style="color:#ff0000;">   data=open('sketch.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'sketch.txt'</span>
            (1.2)split是根据什么来划分,像文件里面是‘:’来划分,1表示划分为两部分;如果一句话中出现多个‘:’,设置了1就只认第一个‘:’进行划分为两部分 


【2】当数据文件不存在时,程序会报错不能正常运行,需要进行代码修改,对打开文件添加异常处理

<pre name="code" class="python">try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,each_spoken)=each_line.split(':',1)
            print(role,end=' ')
            print('said:',end=' ')
            print(each_spoken,end=' ')
        except:
            pass
    data.close()
except:
    print("file error")
 

运行,成功输出;删点数据文件再运行测试一下,不会停止运行



 【3】指定处理异常(异常修改为ValueError,IOError等具体类型)    

try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,each_spoken)=each_line.split(':',1)
            print(role,end=' ')
            print('said:',end=' ')
            print(each_spoken,end=' ')
        except ValueError:
            pass
    data.close()
except IOError:
    print("file error")


【4】sketch.txt这份数据文件,我们上面的操作是读取这份文件,【下面将进行文件的存储读出来的东西找个地方放起来以便使用】

     【4.1】假设将数据文件中两人对白拆分开       

man=[]
other=[]
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(':',1)
            line_spoken=line_spoken.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 file is missing")
print(man)
print(other)
         新建两个列表man跟other用于存放各自对白,strip()是用语句中的空白删除,运行可看到分为了两部分



 【5】现在只是输出在页面,优化它是将输入存入到文件中

man=[]
other=[]
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(':',1)
            line_spoken=line_spoken.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 file is missing")

try:
    man_file=open('man_file.txt','w')
    other_file=open('other_file.txt','w')
    print(man,file=man_file)
    print(other,file=other_file)
    man_file.close()
    other_file.close()
except IOError:
    print("file error")
           【5.1】在第4步骤中添加代码,其中出现了【man_file.txt】跟【other_file.txt】,不用先建这两份文件,你运行程序的时候就会在这个文件夹中自动生成这两份,并且将结果写入其中

           【5.2】data1=open('1.txt')               观察这两种文件打开方式,第一种是读的模式,我只读出来,不做修改,它其实等同于data1=open('1.txt','r'),不写r(read)和

                        data2=open('2.txt','w')         w(write)就默认读,第二种是以写入方式打开,打开文件我要进行写入数据工作

           【5.3】print(man,file=man_file)  意为把man列表数据输出到man_file这份文件中去,就相当于写入里面去了。这里如果是print(”12345”,file=man_file),运行结束                           后你就会看到新建的这份man_file.txt文件中有”12345”这个数据

           【5.4】每打开一份文件最后都要记得关闭,文件名.close()

           【5.5】程序运行好之后跳出的idle编辑窗口显示restart,没有元素输出。这时你查看py文件所在的文件夹中就多了那两个txt文件,里面就是列表的数据。这就是不输出在运行程序中,直接输出保存到文件里面。


【6】错误输出形式优化:之前的错误指明了错误,但是却没有具体说明哪里错误,添加变量来存放错误内容,并转化为字符串(str)类型输出,就能直观看出或查阅该错误

    【6-test】我这里把数据文件删除,然后运行程序,会出现以下情况

说明错误类型以及具体错误,找不到该文件

   【从这里开始,你的每一次运行都要留意了,下面的代码都是只做小修改,每运行一次都会生成两个txt文件,如果你没有删除两个文件就再一次运行新生成的文件会覆盖掉原来的txt文件,因为名字是一样的,不会弹窗报错】


【7】关闭文件优化处理。每次打开文件,如果中间有什么程序错误,在try跟except的保护机制下就会中断这部分程序,不再往下运行,因此文件close()不了。因此这里使用关键字with,其能妥善能关闭数据文件【其他不用改,主要改写模式打开这部分代码】

try:
    with open('man_file.txt','w') as man_file:
        print(man,file=man_file)
    with open('other_file.txt','w') as other_file:
        print(other,file=other_file)
except IOError as err:
    print("file error:"+str(err))
      【7.1】with用法如上,as后面加自己命名的变量名,用于表示txt里面数据,特别留意with语句后面有【:】符号,不可两个with连着写,可以with open('man_file.txt','w') as man_file,open('other_file.txt','w') as other_file:

      【7.2】close不用写,with自己会关闭文件


【8】已写好文件格式优化【像我们看到的新生成的两个文件里面都是列表格式,而且堆在一块】

结合课本第二章模块使用

【模块修改编写】新建py后缀文件【我建的是nester_third.py】,编写函数模块(函数模块作用是将列表(含嵌套列表)中输出到指定文件中,最后是用了print(“数据”,file=文件),应该还记得这种吧,忘记从前面看起)

import sys
def print_list(the_list,indent=False,level=0,fn=sys.stdout):
    for each_line in the_list:
        if isinstance(each_line,list):
            print_list(each_line,indent,level+1,fn)
        else:
            if indent:
                for each_tap in range(level):
                    print("\t",end='',file=fn)
            print(each_line,file=fn)
                     【8.1】4个参数中,第一个参数是填写输入列表,第二个参数是控制是否使用缩进功能,第三个是当使用缩进时根据嵌套列表不同深度控制缩进空格数,第四个是表示之后将结果存入的文件,这里sys.stdout为缺省值,实际使用时参数此项可以为空

                     【8.2】写好py文件之后,根据以往知识将模块包装,安装在本地【不懂的可参考我的博客·【p2】这篇】,安装本地后,使用import功能就能使用该模块

 安装好之后文件夹里面是这样的


                      【8.3】重新改写之前那份代码,将模块功能利用进去【代码与图片详解】

import nester_third
man=[]
other=[]
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(':',1)
            line_spoken=line_spoken.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 file is missing")

try:
    with open('man_file.txt','w') as man_file:
        nester_third.print_list(man,fn=man_file)
    with open('other_file.txt','w') as other_file:
        nester_third.print_list(other,fn=other_file)
except IOError as err:
    print("file error:"+str(err))
    


还记得模块里面的方法吗,print_list(the_list,indent=False,level=0,fn=sys.stdout),上面图片里面只用了两个参数(man,fn=man_file)表示不使用缩进功能所以另外两个不写默认原来的false参数值设置,使用模块让数据更加清晰。运行之后看其中一份man_file里面的数据



再看一下没有使用模块之前的数据格式



 结果显而易见,数据结果可读性高了很多。


【9】当前的数据是一种格式,当需求改变,数据格式需要改变的时候,上面这些处理的代码也要修改了。这就显示的代码的脆弱性,因此需要把数据格式统一。

下面将使用数据的腌制,统一为二进制模式。【代码+代码详解】

import nester_third
import pickle
man=[]
other=[]
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(':',1)
            line_spoken=line_spoken.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 file is missing")

try:
    with open('man_file.txt','wb') as man_file,open('other_file.txt','wb') as other_file:
        pickle.dump(man,man_file)
        pickle.dump(other,other_file)
except IOError as err:
    print("file error:"+str(err))
except pickle.PickleError as perr:
    print("pickle error:"+str(perr))


                                    【wb】是在写模式【w】上的升级,以二进制写入模式打开文件


运行程序,我们可以看到同样会生成两份txt文件,当然如果你文件夹中已经有重名,那么新生成的会直接覆盖,直接看man_file.txt,已经腌制好了(二进制模式)

 反正就是奇奇怪怪的数据,腌制就腌制成这样了


腌制好了,那我们就来尝一尝怎么享用,还是直接运行,在跳出来的idle编辑窗口中键入以下代码

【这里说明下,在idle这个编辑窗口里面我没有import 函数功能模块和pickle,是因为我把她写在了运行文件里面,所以这里不用再导入。如果你们的运行文件中没有写,在这里就要记得import pickle以及import 模块名(处理列表控制元素输出,我的是nester_third,上面有说过)】


关于sketch.txt文件的处理到这里就告一段落了,希望能给你带来帮助,不懂评论支我。

小白请借鉴,高手请指点

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z_pigeon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值