什么是文件:
操作系统提供的操作硬盘的工具
为什么要用文件:
内存无法永久保存数据,要想永久保存数据需要把文件保存到硬盘中,而操作文件就可以实现操作硬件。
文件的打开过程:
1.点击需要打开的文件
2.操作系统接收到命令,将文件路径传给cpu
3.cpu根据路径去硬盘中寻找文件,读到内存中
4.操作系统将调取的文件内容显示出来,可以进行读写保存等操作。
python如何操作文件:
从硬盘中读取数据
用open(file,mode,encoding)函数打开某个具体文件
f = open(‘day7practice.txt‘,‘r‘) print(f.readable()) # 判断当前文件是否可读 print(f.writable()) # 判断当前文件是否可写 f.close() # 回收操作系统资源 del f # 回收变量资源 del f得在f.close()后,否则无法回收系统资源 >>True >>False
python 使用with关键字来进行回收
with open(‘day7practice.txt‘,‘r‘) as f:
print(f.readable())
>> True #执行完子代码后with会自动执行f.close()
可用with同时打开多个文件,用逗号分隔开即可
with open(‘day7practice.txt‘,‘r‘) as read_f,open(‘lll.txt‘,w") as write_f:
data = read_f.read()
write_f.write(data) # 在lll.txtx中写入从day7practice.txt的内容
指定操作文本文件的字符编码
f = open(‘lll.txt‘,‘r‘,‘encoding=‘utf-8‘)
文件的操作模式:
r(默认):只读 如果文件不存在,会报错
w:只写 如果文件不存在,新建一个文件;如果文件内存在数据,清空数据,指针到文件开头,重新写入内容
a:只追加 如果文件不存在,新建一个文件;如果文件内存在数据,指针跑到文件尾部,新内容写在旧内容后
1.r模式的使用
with open(‘lll.txt‘,mode = ‘r‘,encoding = ‘utf-8‘) as f:
print(f.readline()) # 执行一次,打印一行内容
print(f.readlines()) # 读取每一行内容,存放于列表中
res = f.read() #将文件内容从硬盘全部读入内存,赋值给res
2.w模式的使用
with open(‘lll.txt‘,mode = ‘w‘,encoding = ‘utf-8‘) as f:
f.write(‘I\n‘)
f.write(‘am\n‘)
f.write(‘your\n‘)
f.write(‘dad‘\n)
f.write(‘I\nam\nyour\ndad‘)
3.a 模式的使用
with open(‘lll.txt‘,mode = ‘a‘,encoding = ‘utf-8‘) as f:
f.write(‘my\n‘)
f.write(‘son\n‘)
原文:https://www.cnblogs.com/littleb/p/11815654.html