Python Replace Line By Index Number
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?
Solution 1:
If you wish to count iterations, you should use enumerate()
withopen('fin.txt') as fin, open('fout.txt', 'w') as fout:
for i, item inenumerate(fin, 1):
if i == 7:
item = "string\n"
fout.write(item)
Solution 2:
something likes:
count = 0withopen('input') as f:
withopen('output', 'a+') as f1:
for line in f:
count += 1if count == 7:
line = "string\n"
f1.write(line)
Solution 3:
from tempfile import mkstemp
from shutil import move
from os import remove, close
defreplace(file_path, pattern, subst):
# Create temp file
fh, abs_path = mkstemp()
withopen(abs_path, 'w') as new_file:
withopen(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....
Solution 4:
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
withopen(filename, "a+") as uf, open(filename2, "w+") as outf:
for i, item inenumerate(uf, 1):
#Starts for loop with the "normal" counting numbers at 1 instead of 0if 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 withprint(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)
Post a Comment for "Python Replace Line By Index Number"