从零学python系列之从文件读取和保存数据

 更新时间:2014年05月23日 10:23:38   作者:  
在Python一般都是运用内置函数open()与文件进行交互,下面说说具体用法

在HeadFirstPython网站中下载所有文件,解压后以chapter 3中的“sketch.txt”为例:

 

新建IDLE会话,首先导入os模块,并将工作目录却换到包含文件“sketch.txt”的文件夹,如C:\\Python33\\HeadFirstPython\\chapter3

复制代码 代码如下:

>>> import os
>>> os.getcwd()    #查看当前工作目录
'C:\\Python33'
>>> os.chdir('C:/Python33/HeadFirstPython/chapter3')   #切换包含数据文件的文件夹
>>> os.getcwd()     #查看切换后的工作目录
'C:\\Python33\\HeadFirstPython\\chapter3'

打开文件“sketch.txt”,读取并显示前两行:

复制代码 代码如下:

>>> data=open('sketch.txt')
>>> print(data.readline(),end='')
Man: Is this the right room for an argument?
>>> print(data.readline(),end='')
Other Man: I've told you once.

回到文件起始位置,使用for语句处理文件中的每行,最后关闭文件:

复制代码 代码如下:

>>> data.seek(0)   #使用seek()方法回到文件起始位置
>>> for each_line in data:
    print(each_line,end='')

   
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!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
>>> data.close()

读取文件后,将不同role对应数据分别保存到列表man和other:

复制代码 代码如下:

import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\chapter3')
man=[]    #定义列表man接收Man的内容
other=[]  #定义列表other接收Other Man的内容

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 datafile is missing!')
print (man)
print (other)

Tips:

使用open()方法打开磁盘文件时,默认的访问模式为r,表示读,不需要特意指定;

要打开一个文件完成写,需要指定模式w,如data=open("sketch.txt","w"),如果该文件已经存在则会清空现有内容;

要追加到一个文件,需要指定模式a,不会清空现有内容;

要打开一个文件完成写和读,且不清空现有内容,需要指定模式w+;

 例如,将上例中保存的man和other内容以文件方式保存时,可修改如下:

复制代码 代码如下:

import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\chapter3')
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 datafile is missing!')

try:
    man_file=open('man.txt', 'w')      #以w模式访问文件man.txt
    other_file=open('other.txt','w')   #以w模式访问文件other.txt
    print (man, file=man_file)           #将列表man的内容写到文件中
    print (other, file=other_file)
except IOError:
    print ('File error')
finally:
    man_file.close()
    other_file.close()

但是第26行print()为什么会报错?“syntax error while detecting tuple”,有大神能给解惑一下不

相关文章

  • unittest+coverage单元测试代码覆盖操作实例详解

    unittest+coverage单元测试代码覆盖操作实例详解

    这篇文章主要为大家详细介绍了unittest+coverage单元测试代码覆盖操作的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • Python实现切割mp3片段并降低码率

    Python实现切割mp3片段并降低码率

    MoviePy是一个基于Python的视频编辑库,它提供了创建、编辑、合并、剪辑和转换视频的功能,所以本文主要介绍如何使用moviepy来分割音频流并降低码率,感兴趣的可以了解下
    2023-08-08
  • python实现模拟键盘鼠标重复性操作Pyautogui

    python实现模拟键盘鼠标重复性操作Pyautogui

    这篇文章主要为大家详细介绍了python如何利用Pyautogui模拟键盘鼠标重复性操作,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-11-11
  • 教你用python将数据写入Excel文件中

    教你用python将数据写入Excel文件中

    Python作为一种脚本语言相较于shell具有更强大的文件处理能力,下面这篇文章主要给大家介绍了关于如何用python将数据写入Excel文件中的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-02-02
  • python爬虫入门教程之糗百图片爬虫代码分享

    python爬虫入门教程之糗百图片爬虫代码分享

    这篇文章主要介绍了python爬虫入门教程之糗百图片爬虫代码分享,本文以抓取糗事百科内涵图为需求写了一个爬虫,,需要的朋友可以参考下
    2014-09-09
  • python免杀技术shellcode的加载与执行

    python免杀技术shellcode的加载与执行

    本文主要介绍了python免杀技术shellcode的加载与执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • python-opencv如何读取图片及尺寸修改

    python-opencv如何读取图片及尺寸修改

    这篇文章主要介绍了python-opencv如何读取图片及尺寸修改,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • python计算机视觉OpenCV入门讲解

    python计算机视觉OpenCV入门讲解

    这篇文章主要介绍了python计算机视觉OpenCV入门讲解,关于图像处理的相关简单操作,包括读入图像、显示图像及图像相关理论知识
    2022-06-06
  • Python批量获取基金数据的方法步骤

    Python批量获取基金数据的方法步骤

    这篇文章主要介绍了Python批量获取基金数据的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • python程序快速缩进多行代码方法总结

    python程序快速缩进多行代码方法总结

    在本篇文章里小编给大家整理了关于python程序如何快速缩进多行代码的相关知识点,需要的朋友们学习下。
    2019-06-06

最新评论