Guest User

Untitled

a guest
May 27th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. # HOW TO WORK:
  5. # >> writeline_in_file("./folder/myfile.txt", 12, "I write this line in line 12")
  6. # if you want another carriage return read "open() > newline" python manual
  7.  
  8.  
  9. def writeline_in_file(path, numline, str, cr=None):
  10. try:
  11. with open(path, 'r') as file_data:
  12. lines_data = file_data.readlines()
  13. lines = copy(lines_data)
  14. except FileNotFoundError:
  15. return -1
  16. if numline < 1:
  17. return -1
  18. nbline = len(lines)
  19. for i in range(nbline):
  20. lines[i] = lines[i].replace('\r\n', '')
  21. lines[i] = lines[i].replace('\r', '')
  22. lines[i] = lines[i].replace('\n', '')
  23. while nbline <= numline:
  24. nbline += 1
  25. lines.append("")
  26. lines[numline-1] = str
  27. with open(path, "w", newline=cr) as file:
  28. for item in lines:
  29. file.write("%s\n" % (item))
  30. del lines
  31. return 0
Add Comment
Please, Sign In to add comment