CSDN话题挑战赛第2期
参赛话题:学习笔记
Python学习 - 语法入门:https://blog.csdn.net/wanzijy/article/details/125287855
Python学习 - 数据类型:https://blog.csdn.net/wanzijy/article/details/125341568
Python学习 - 流程控制:https://blog.csdn.net/wanzijy/article/details/125400906
Python学习 - 运算符(操作符):https://blog.csdn.net/wanzijy/article/details/125387919
Python学习 - 列表:https://blog.csdn.net/wanzijy/article/details/125457990
Python学习 - 字典:https://blog.csdn.net/wanzijy/article/details/125567225
Python学习 -元组和集合:https://blog.csdn.net/wanzijy/article/details/125577609
Python学习 - 函数(1):https://blog.csdn.net/wanzijy/article/details/125669084
Python学习 - 函数(2):https://blog.csdn.net/wanzijy/article/details/125739981
Python学习 - 类与对象:https://blog.csdn.net/wanzijy/article/details/125826952
Python学习 - 面向对象之封装:https://blog.csdn.net/wanzijy/article/details/125902925
Python学习 - 面向对象之继承:https://blog.csdn.net/wanzijy/article/details/125963829
Python学习 - 面向对象之多态:https://blog.csdn.net/wanzijy/article/details/127140632
Python - 文件操作(1):https://blog.csdn.net/wanzijy/article/details/127099071
Python - 文件操作(2):https://blog.csdn.net/wanzijy/article/details/127150189
Python学习 - 垃圾回收、特殊方法和模块:https://blog.csdn.net/wanzijy/article/details/126202999
Python学习 - 异常处理:https://blog.csdn.net/wanzijy/article/details/126803672
通过 Python 程序来对计算机中的文件进行增删改查的操作
I/O (Input / Output)
操作文件的步骤:
open(file, encoding=None)
file_name = 'Demo.txt'
file_obj = open(file_name, encoding='utf-8')
在表示路径时,可以使用 “. .” 来返回一级目录
如果目标文件距离当前文件比较远,此时可以使用绝对路径(要从磁盘的根目录开始写)
当我们获取文件对象以后,所有的对文件的操作,都是对这个对象的操作
当关闭文件之后,就不能再通过该对象操作文件
关闭方式:
file_name = 'Demo.txt'
file_obj = open(file_name, encoding='utf-8')
print(file_obj)
file_obj.close()
with open(file_name, encoding='utf-8') as file_obj:
print(file_obj)
结合以前学的 try-catch 语句,那么正规的打开文件的代码应该是:
file_name = 'Demo.txt'
try:
with open('asas', encoding='utf-8') as file_obj:
print(file_obj)
except FileNotFoundError:
print(f'{file_name}文件不存在')
当调用 open() 来打开文件时,可以将文件分成两种类型:
open() 打开文件时,默认是以文本形式打开的,但是 open() 默认的编码为“None”
当处理文本文件时,必须要指定文件的编码
file_name = 'Demo.txt'
try:
with open(file_name, encoding='utf-8') as file_obj:
content = file_obj.read()
print(content)
except FileNotFoundError:
print(f'{file_name}文件不存在')
如果直接调用 read(),会将文本中的所有内容全部一次性读取出来
但是如果文件较大的话,会将内容加载到内存中,容易导致内存泄露
read()
当读取大文件时,可以利用 size 参数和循环来读取
file_name = 'Demo.txt'
try:
with open(file_name, encoding='utf-8') as file_obj:
chunk = 50
while True:
content = file_obj.read(chunk)
if(not content): # 空串会自动转为False
break
print(content, end='') # end='' 的意思是将换行去掉
except FileNotFoundError:
print(f'{file_name}文件不存在')
readlines() 直接读取一行,但是会一次性将读取到的内容返回,将其封装到一个列表中返回
import pprint
file_name = 'Demo.txt'
try:
with open(file_name, encoding='utf-8') as file_obj:
pprint.pprint(file_obj.readlines())
except FileNotFoundError:
print(f'{file_name}文件不存在')
也可以通过 for 循环去读取文件对象中的内容
file_name = 'Demo.txt'
try:
with open(file_name, encoding='utf-8') as file_obj:
for t in file_obj:
print(t, end='')
except FileNotFoundError:
print(f'{file_name}文件不存在')