Search code examples
pythonfilereadlines

How to read and write multiple lines of a text file in Python


I am trying to read and write multiple lines of a text file in Python. My goal is to specify the rows which I want to be changed with the input I give to the script. The script is working when specifying a single row, but not with multiple rows.

For example lets say I have this file:

Item 1
Item 2
Item 3

When trying to do the following for a single line it is working fine:

a_file = open("filename.yml", "r")
list_of_lines = a_file.readlines()
list_of_lines[1] = "Item: " + (input('Input: ')) + "\n"

a_file = open("filename.yml", "w")
a_file.writelines(list_of_lines)
a_file.close()

But I cant seem to figure out how to apply the same input for multiple lines of text file. What I've tried but didn't work:

a_file = open("filename.yml", "r")
list_of_lines = a_file.readlines()
list_of_lines[1][2] = "Item: " + (input('some input: ')) + "\n"

a_file = open("filename.yml", "w")
a_file.writelines(list_of_lines)
a_file.close()

Solution

  • Thy using a for loop:

    with open('file.txt', 'r') as f:
        list_of_lines = f.readlines()
        t = f"Item {input('some input: ')}\n"
        for i in range(len(list_of_lines)):
            if i in [1, 2]:
                list_of_lines[i] = t
    
    with open("file.txt", "w") as f:
        f.writelines(list_of_lines)
    

    file.txt:

    Item 1
    Item 2
    Item 3
    

    Input:

    some input: hello
    

    Resulting file.txt:

    Item 1
    Item hello
    Item hello
    

    You can also use a list comprehension with the built-in enumerate method:

    t = f"Item {input('some input: ')}\n"
    d = [1, 2]
    
    with open('file.txt', 'r') as f:
        list_of_lines = [t if i in d else v for i, v in enumerate(f)]
        
    with open("file.txt", "w") as f:
        f.writelines(list_of_lines)