file_manager.py 844 B

123456789101112131415161718192021222324252627282930313233
  1. """
  2. @ Author: Mr.Hat
  3. @ Date: 2024/3/30 14:05
  4. @ Description:
  5. @ History:
  6. """
  7. from typing import Optional
  8. def file_to_list(
  9. filename: str
  10. ):
  11. with open(filename, 'r+') as f:
  12. return list(filter(bool, f.read().splitlines()))
  13. def str_to_file(file_name: str, msg: str, mode: Optional[str] = "a"):
  14. with open(
  15. file_name,
  16. mode
  17. ) as text_file:
  18. text_file.write(f"{msg}\n")
  19. def shift_file(file):
  20. with open(file, 'r+') as f: # open file in read / write mode
  21. first_line = f.readline() # read the first line and throw it out
  22. data = f.read() # read the rest
  23. f.seek(0) # set the cursor to the top of the file
  24. f.write(data) # write the data back
  25. f.truncate() # set the file size to the current size
  26. return first_line.strip()