首页 > 编程 > Python > 正文

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

2020-02-23 05:24:20
字体:
来源:转载
供稿:网友

在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)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表