file-read-write-compress.py 679 B

123456789101112131415161718192021222324252627282930313233
  1. import os, gzip
  2. def read_file(fname, compress=False):
  3. if compress:
  4. f = gzip.GzipFile(fname, 'rb')
  5. else:
  6. f = open(fname, 'rb')
  7. try:
  8. data = f.read()
  9. finally:
  10. f.close()
  11. return data
  12. def write_file(data, fname, compress=True):
  13. #print(os.getcwd())
  14. if compress:
  15. f = gzip.GzipFile(fname, 'wb')
  16. else:
  17. f = open(fname, 'wb')
  18. try:
  19. f.write(data)
  20. finally:
  21. f.close()
  22. data = read_file('hey.txt')
  23. print(data)
  24. data = read_file('hey.gz', True)
  25. print(data)
  26. write_file(b'This is a hello string', 'hello.txt', False)
  27. write_file(b'This is a hello string in compress format', 'hello.txt.gz')