Python的IO流-1
很简单的内容,必要的东西写在了注释里:
1 import os
2
3 print('当前工作目录:'+os.getcwd()) # 这个方法可以得到当前程序的工作目录
4 try:
5 f = open('F:/xx1/xx2/Game.txt', 'r') # 为了安全性,要调用close方法;同时为了保证能够调用close方法,需要放在try,finally里面
6 print(f.read())
7 finally:
8 f.close()
9
10 with open('F:/xx1/xx2/Game.txt') as file: # 这样就不必使用try,finally调用close方法了
11 content = file.read()
12 print(content)
13 file.close()
14
15 with open('F:/xx1/xx2/Nothing.txt') as file:
16 for line in file: # 一行一行读取
17 print(line.rstrip()) # 去除后面的'\n'
18 file.close()
19
20 with open('F:/xx1/xx2/Game.txt', 'w') as file: # 表示写入,这样会覆盖原内容,如果不想覆盖,用'a'
21 file.write("Oh,that's for sure!")
22 file.close()
23
24 with open('F:/xx1/xx2/Game.txt', 'r') as file:
25 print(file.read())
26 file.close()
27
28 with open('F:/魔法世界.jpg', 'rb') as f: # 读取二进制文件
29 print(f.read()) # 读取内容是用十六进制表示的字节
附:异常处理:
1 def foo(n): 2 return 10 / int(n) 3 4 5 def bar(s): 6 return foo(s) * 2 7 8 9 def main(): 10 try: 11 bar('0') 12 except Exception as e: 13 print('Error:', e) 14 finally: 15 print('Finally...') 16 17 18 main()