文本文件
二进制文件
# 打开文件 file = open("README") # 读取文件 text = file.read() print(text) # 关闭文件 file.close()
# 打开文件 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("程序执行完毕")
# 打开 file_read = open("README") file_write = open("README[复件]", "w") # 读取 text = file_read.read() # 写入 file_write.write(text) # 关闭 file_read.close() file_write.close()
# 打开文件 file = open("README") # 读取文件 while True: text = file.readline() # 判断是否读取到内容 if not text: break print(text) # 关闭 file.close()
大文件复制
# 打开 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()