Is it possible in Python to replace the content of a line in a file by its index number?
Would something like a line.replace to do this procedure?
Is it possible in Python to replace the content of a line in a file by its index number?
Would something like a line.replace to do this procedure?
If you wish to count iterations, you should use enumerate()
with open('fin.txt') as fin, open('fout.txt', 'w') as fout:
for i, item in enumerate(fin, 1):
if i == 7:
item = "string\n"
fout.write(item)
something likes:
count = 0
with open('input') as f:
with open('output', 'a+') as f1:
for line in f:
count += 1
if count == 7:
line = "string\n"
f1.write(line)
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace(file_path, pattern, subst):
# Create temp file
fh, abs_path = mkstemp()
with open(abs_path, 'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
close(fh)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
You can use the above function to replace a particular line from a file, and you can call this function when needed as:
replace("path_of_File\\test.txt", "lien that needs to be changed", "changed to ")
hope this is the one you might be looking for....
Well I used some of the answers above and allowed for user input to be put in the file. This also prints out the line that the user input will replace.
Note that filename is a placeholder the true filename.
import os, sys
editNum=int(editLine)
filename2="2_"+filename
with open(filename, "a+") as uf, open(filename2, "w+") as outf:
for i, item in enumerate(uf, 1):
#Starts for loop with the "normal" counting numbers at 1 instead of 0
if i != editNum:
#If the index number of the line is not the one wanted, print it to the other file
outf.write(item)
elif i == editNum:
#If the index number of the line is the one wanted, ask user what to replace line with
print(item)
filereplace=raw_input("What do you want to replace this line with? ")
outf.write(filereplace)
#Removes old file and renames filename2 as the original file
os.remove(filename)
os.rename(filename2, filename)