![[Python 从入门到放弃] 5. 文件与异常(一) [Python 从入门到放弃] 5. 文件与异常(一)](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
1.文件操作:
文件操作包含读/写
从文件中读取数据
向文件写入数据
Python中内置了open()方法用于文件操作 (更多关于open()BIF介绍 阅读此篇)
基本模板:
1.获取文件对象
2.文件处理:读/写/...
3.关闭文件
# .打开文件 the_file=open('f://test.txt') # f://test.txt 是绝对路径
.open(.为什么要关闭文件: 打开文件之后,会占用文件资源 在不需要使用时,应该及时关闭文件 '''
2.简单的文件读取
在python中基本的输入机制是基于行的:
(1).现在有一个文本文件:
filename:test.txt # 文件名 filePath:f:/test.txt # 路径 fileContent: # 文件内容 Man:Is this the right room for an argument?Other Man:I've told once.Man:No you haven't!Other Man:Yes I have.Man:When?Other Man:Just now.Man:No you didn't......Other Man:Now let's get one thing quite clear:I most definitely told you!Man:Oh no you did't!Other Man:Oh yes I did! '''你可以参照文件信息,在f盘创建一个'''
(2).开始读取:
the_file=open('f://test.txt') # 为什么路径是f://test.txt 不是f:/test.txt? # 因为在windows就得使用此等格式 在‘/’前加一个 # 也可以这样写: open(r'f:/test.txt') 加上r的指明读取原始字符串:后面附带的字符串是什么就用什么 不需要转义 print(the_file.readline()) the_file.close()
运行结果:
读取了文件中的第一行
readline()函数:读取一行
现在改变一下代码:
the_file=open('f://test.txt') print(the_file.readline()) print(the_file.readline()) # 使用了两个相同的语句 the_file.close()
运行结果:
结果不是输出两个相同的文件内容:
得益于文件指针,在读取该行之后,
文件指针会自动指向下一行
使用即使相同的读取语句
指针也会遵循一行行的原则指向
如何人为控制文件指针指向?
比如:当你想两次输出都输出第一行时:
可以参考seek()方法:
the_file=open('f://test.txt') print(the_file.readline()) the_file.seek(0) # 将文件指针设置在起始位置 也就是往回调 print(the_file.readline()) the_file.close()
执行结果:
(3)输出文本文件中的全部内容
方法一:使用迭代器,逐一输出:
the_file=open('f://test.txt') for line in the_file: print(line) the_file.close()
运行结果:
# 全部输出文件内容 Man:Is this the right room for an argument? Other Man:I've told once. Man:No you haven't! Other Man:Yes I have. Man:When? Other Man:Just now. Man:No you didn't ...... Other Man:Now let's get one thing quite clear:I most definitely told you! Man:Oh no you did't! Other Man:Oh yes I did!
方法二:使用read():
the_file=open('f://test.txt') print(the_file.read()) the_file.close()
read()能够将文本文件内容作为一个大字符串返回
执行结果:
Man:Is this the right room for an argument? Other Man:I've told once. Man:No you haven't! Other Man:Yes I have. Man:When? Other Man:Just now. Man:No you didn't ...... Other Man:Now let's get one thing quite clear:I most definitely told you! Man:Oh no you did't! Other Man:Oh yes I did!
当需要逐行处理时,使用方法一迭代的方法
当直接输出而不需要做其它时,使用read()方法
(4)readlines():
readline()方法是逐行读取,并返回所读取的字符串
readlines()方法是读取多行,并返回一个列表
测试一下:
the_file=open('f://test.txt') print(the_file.readlines()) the_file.close()
执行结果:
['Man:Is this the right room for an argument?\n', "Other Man:I've told once.\n", "Man:No you haven't!\n", 'Other Man:Yes I have.\n', 'Man:When?\n', 'Other Man:Just now.\n', "Man:No you didn't\n", '......\n', "Other Man:Now let's get one thing quite clear:I most definitely told you!\n", "Man:Oh no you did't!\n", 'Other Man:Oh yes I did!']
每一行都作为列表的数据项
并包含换行符’\n‘