file_util.py 914 B

123456789101112131415161718192021222324252627282930313233
  1. import os
  2. def read_dir(root):
  3. file_path_list = []
  4. for file_path, dirs, files in os.walk(root):
  5. for file in files:
  6. file_path_list.append(os.path.join(file_path, file).replace('\\', '/'))
  7. file_path_list.sort()
  8. return file_path_list
  9. def read_file(file_path):
  10. file_object = open(file_path, 'r')
  11. file_content = file_object.read()
  12. file_object.close()
  13. return file_content
  14. def write_file(file_path, file_content):
  15. if file_path.find('/') != -1:
  16. father_dir = '/'.join(file_path.split('/')[0:-1])
  17. if not os.path.exists(father_dir):
  18. os.makedirs(father_dir)
  19. file_object = open(file_path, 'w')
  20. file_object.write(file_content)
  21. file_object.close()
  22. def write_file_not_cover(file_path, file_content):
  23. father_dir = '/'.join(file_path.split('/')[0:-1])
  24. if not os.path.exists(father_dir):
  25. os.makedirs(father_dir)
  26. file_object = open(file_path, 'a')
  27. file_object.write(file_content)
  28. file_object.close()