Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # HOW TO WORK:
- # >> writeline_in_file("./folder/myfile.txt", 12, "I write this line in line 12")
- # if you want another carriage return read "open() > newline" python manual
- def writeline_in_file(path, numline, str, cr=None):
- try:
- with open(path, 'r') as file_data:
- lines_data = file_data.readlines()
- lines = copy(lines_data)
- except FileNotFoundError:
- return -1
- if numline < 1:
- return -1
- nbline = len(lines)
- for i in range(nbline):
- lines[i] = lines[i].replace('\r\n', '')
- lines[i] = lines[i].replace('\r', '')
- lines[i] = lines[i].replace('\n', '')
- while nbline <= numline:
- nbline += 1
- lines.append("")
- lines[numline-1] = str
- with open(path, "w", newline=cr) as file:
- for item in lines:
- file.write("%s\n" % (item))
- del lines
- return 0
Add Comment
Please, Sign In to add comment