一、导入os模块,打印当前工作目录
import os
os.getcwd()
运行结果:'/Users/shadow/Documents'
二、切换包含数据的文件目录
os.chdir('../HeadFirstPython/chapter3')
os.getcwd()
运行结果:'/Users/shadow/HeadFirstPython/chapter3'
三、打开文件目录下的一个文件,返回一个名为data的文件对象
data= open('sketch.txt')
print(data.readline(), end='')
运行结果:hello world
print(data.readline(), end='')
运行结果:shadow study python
ps:readline方法从文件读取一行
四、使用seek方法退回到文件起始位置
data.seek(0)
五、使用for循环处理文件中的每一行
for each_line in data:
print(each_line, end='')
运行结果:
hello world
shadow study python
六、关闭文件
data.close()