首页 > 技术文章 > python io操作

tele-share 2019-03-14 21:51 原文

一次性读取

 1 # 读取文件
 2 
 3 # 默认打开文件的方式是只读
 4 file = None
 5 try:
 6     file = open("f:/test.sql")
 7     print(file.name)  # f:/test.sql
 8 
 9     # read是一次性读取,调用read之后会把指针移动到文件的末尾,再次调用返回空字符串
10     content = file.read()
11 
12     # print("----" + file.read())
13     print(content)
14 except Exception as log:
15     print("找不到文件")
16 finally:
17     if file:
18         file.close()
19 
20 # 使用with语句,with语句会自动帮我们调用close()
21 with open("f:/test.sql") as f:
22     print(f.read())
23 
24 # 使用with 可以创建单层级文件
25 # with open("f:/ooooooooooooooooa.sql","w") as f:
26 #     f.write("asd")

逐行读取

 1 # 逐行读取
 2 
 3 file = None
 4 try:
 5     file = open("f:/test.sql")
 6 
 7     line = file.readline()
 8     while line is not None and line.strip() != "":
 9         print(line)
10         line = file.readline()
11 
12 except Exception as info:
13     print("文件未找到")
14 finally:
15     if file is not  None:
16         file.close()

 逐行读取并写入

 1 # 逐行读取并写入
 2 rs = None
 3 ws = None
 4 try:
 5     rs = open("f:/test.sql")
 6     ws = open("f:/test_copy.sql", "w")
 7 
 8     # 读取并写入
 9     while True:
10         line = rs.readline()
11 
12         # 如果line为None或者line为空字符串
13         if line is None or line.strip() == "": # 或者 not line
14             break
15         ws.write(line)
16 
17 
18 except Exception as info:
19     print(info)
20 finally:
21     if rs:
22         rs.close()
23     if ws:
24         ws.close()

 字节流

 1 # -*- coding: utf-8 -*-
 2 # @author: Tele
 3 # @Time  : 2019/04/04 下午 12:17
 4 # 字节流读写
 5 rs = open("F:/ftp_mypc/a.flv", "rb")
 6 ws = open("f:/a_copy.flv", "wb")
 7 buffer = 1024
 8 while True:
 9     content = rs.read(buffer)
10     if not content:
11         break
12     ws.write(content)
13 
14 if rs:
15     rs.close()
16 if ws:
17     ws.close()

 

推荐阅读