-1

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?

HightronicDesign
  • 699
  • 1
  • 9
  • 15
  • Replace line 7 of a specific file with a string? – Stephen Lin May 11 '15 at 06:29
  • possible duplicate of [Search and replace a line in a file in Python](http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – dting May 11 '15 at 06:30
  • @m170897017 Yes of a specific file, the file is dynamic and i have a function which gets me the line number i want to replace, but how can i replace the found line now ^^ ? – HightronicDesign May 11 '15 at 06:33

4 Answers4

4

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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

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)
hungnv
  • 152
  • 8
0
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....

Shaik
  • 400
  • 3
  • 9
0

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)