70_file.py 806 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. try:
  2. import os
  3. import io
  4. print("[`os` Test Enabled]")
  5. except ImportError:
  6. exit(0)
  7. a = open('123.txt', 'wt')
  8. a.write('123')
  9. a.write('456')
  10. a.close()
  11. with open('123.txt', 'rt') as f:
  12. assert f.read() == '123456'
  13. with open('123.txt', 'a') as f:
  14. f.write('测试')
  15. # default mode is 'r'
  16. with open('123.txt') as f:
  17. assert f.read() == '123456' + '测试'
  18. assert os.path.exists('123.txt')
  19. os.remove('123.txt')
  20. assert not os.path.exists('123.txt')
  21. with open('123.bin', 'wb') as f:
  22. f.write('123'.encode())
  23. f.write('测试'.encode())
  24. def f():
  25. with open('123.bin', 'rb') as f:
  26. b = f.read()
  27. assert isinstance(b, bytes)
  28. assert b == '123测试'.encode()
  29. f()
  30. assert os.path.exists('123.bin')
  31. os.remove('123.bin')
  32. assert not os.path.exists('123.bin')