创建一个文件夹HeadFirstPython,另外创建一个子文件夹chapter3。然后在Head First Python官方网站下载sketch.txt,把它保存到chapter3文件夹。
打开IDLE会话,导入OS模块,将当前工作目录切换到包含刚下载的数据文件的文件夹:
>>> import os #导入公共模块
>>> os.getcwd() #获取当前工作目录
'C:\\Program Files\\Python36'
>>> os.chdir('D:\\test\\HeadFirstPython\\chapter3') #切换工作目录
>>> os.getcwd()
'D:\\test\\HeadFirstPython\\chapter3'
>>> data=open('sketch.txt') #打开指定文件
>>> print(data.readline(),end='') #data.readline() 读取文件一行内容 end='' 关闭”在输出中自动包含换行”的默认行为。
Man: Is this the right room for an argument?
>>> print(data.readline(),end='')
Other Man: I've told you once.
>>> data.seek(0) #回到文件起始位置 或者使用tell() 获取当前文件读取指针的位置
0
>>> 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.........省略
>>> data.close() #关闭文件 处理完文件后一定要将它关闭
>>>
涉及方法:
getcwd():获取当前工作目录
chdir():切换工作目录
open(fileName):打开文件
readline():读取文件一行内容
seek(0):回到文件起始位置
tell():获取当前文件读取指针的位置
split(beans,num): 根据标识符beans切割字符串,返回一个字符串列表。num:代表分割为几部分,1代表两部分,默认为不限制