基础DAY13-文件
文本文件
二进制文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 打开文件 file = open("README") # 读取文件 text = file.read() print(text) # 关闭文件 file.close()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 打开文件 try: file = open("README") except Exception as result: print("%s" % result) else: # 读取文件 text = file.read() print(text) print("-"*50) # 读取文件后文件指针会改变 text = file.read() print(text) # 关闭文件 file.close() finally: print("程序执行完毕")
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 打开 file_read = open("README") file_write = open("README[复件]", "w") # 读取 text = file_read.read() # 写入 file_write.write(text) # 关闭 file_read.close() file_write.close()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 打开文件 file = open("README") # 读取文件 while True: text = file.readline() # 判断是否读取到内容 if not text: break print(text) # 关闭 file.close()
大文件复制
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 打开 file_read = open("README") file_write = open("README[复件]", "w") # 读取 while True: # 读取一行内容 text = file_read.readline() # 判断是否读取到内容 if not text: break # 写入 file_write.write(text) # 关闭 file_read.close() file_write.close()