【Python实战04】文件读取和split方法的使用

之前我们使用到的数据都是自己在控制台进行定义的,在Python处理数据时,很多情况下要多一些文件中的数据进行整理,所以就很有必要对一个文件进行读取,下面我们就看看如果使用Python去读取一个文件。首先准备一个文件,等会我们会对这个文件进行读取,这里我把文件放到D:\python\file下,文件名为:sketch.txt,文件的内容如下:Man: Is this the righ
摘要由CSDN通过智能技术生成

之前我们使用到的数据都是自己在控制台进行定义的,在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.
>>> 
这里我们尝试着读取了其中的两行,
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值