之前我们使用到的数据都是自己在控制台进行定义的,在Python处理数据时,很多情况下要多一些文件中的数据进行整理,所以就很有必要对一个文件进行读取,下面我们就看看如果使用Python去读取一个文件。
首先准备一个文件,等会我们会对这个文件进行读取,这里我把文件放到D:\python\file下,文件名为: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!
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!
读取文件
下面我们首先要做的工作是定位python shell到我们文件所在的文件夹下,这样才能找到我们的文件,通过以下的命令进行定位:
>>> import os
>>> os.getcwd()
'D:\\Python33'
>>> os.chdir('d:\\python\\file')
>>> os.getcwd()
'd:\\python\\file'
>>>
好了,这里我们注意首先导入了os包,然后通过os.chdir()方法定位到我们需要的位置,然后确认下就可以了,这里我定位到了d:\python\file文件夹下了。
然后我们就可以尝试的去读取文件的内容了,这里我们先一行一行的去读,如下:
>>> 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.
>>>
这里我们尝试着读取了其中的两行,