Skip to content

Instantly share code, notes, and snippets.

@borrougagnou
Last active May 22, 2018 21:06
Show Gist options
  • Save borrougagnou/8fa51883782e6cf7a9bbadf9f3e71e95 to your computer and use it in GitHub Desktop.
Save borrougagnou/8fa51883782e6cf7a9bbadf9f3e71e95 to your computer and use it in GitHub Desktop.
Write - change 1 line anywhere in python file
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment