1

I am new to Python and how do I replace a particular word in a line in a text file in Python? Like suppose I have a text file:

1 2 3 4 5
1 2 3 1 5

How do I replace the second 1 with 4 in the second line in Python?

Saaheer Purav
  • 39
  • 3
  • 5
  • You might want to provide a little more context to the question. Are you looking for a generic swapping script? Or do you want to correct certain lines in the file to the correct line? – Jamie Jan 30 '20 at 09:59

5 Answers5

1

I don't know what file you're looking at, or whether it's truly parsed, but it seems like you're just learning Python, so here are some examples.

First, you could read the file, line by line, and split each line by whitespace.

>>> lines = [l.split() for l in open('foobar.txt').readlines()]
>>> lines
[['1', '2', '3', '4', '5'], ['1', '2', '3', '1', '5']]

So now we have a list of lines, and each line in the list is a list of words. We can manipulate it however we see fit. Eg,

>>> lines[1][3] = 999
>>> lines
[['1', '2', '3', '4', '5'], ['1', '2', '3', 999, '5']]

We can iterate over each word and each line:

>>> for line_number, line in enumerate(lines):
        for word_number, word in enumerate(line):
             print(f'Line {line_number}, word {word_number}: {word}')

Line 0, word 0: 1
Line 0, word 1: 2
Line 0, word 2: 3
Line 0, word 3: 4
Line 0, word 4: 5
Line 1, word 0: 1
Line 1, word 1: 2
Line 1, word 2: 3
Line 1, word 3: 999
Line 1, word 4: 5
Ken Kinder
  • 12,654
  • 6
  • 50
  • 70
0

You can replace by position using this solution

s = list("1 2 3 1 5")
s[6]="4";
print("".join(s))
Panciz
  • 2,183
  • 2
  • 30
  • 54
0

let suppose this data is in input.txt

file = open("input.txt",'r')
file_new=open("new_input.txt",'w+')
lines = file.readlines
linenumber=0
for line in lines:
    linenumber=linenumber+1
    if linenumber=2:

        line = str(line).replace('1','4')
    file_new.writelines(line)
file.close()
file_new.close()

new_input.txt will have 2nd line's 1 replaced with 4

  • That doesn't work correctly. instead `if linenumber=2` use `if linenumber==2` ! But still, that would change ALL '1's in the 2nd Line, but as far as I can tell he just wants to change the 2nd 1 in the 2nd Line... – sxeros Jan 30 '20 at 10:16
0
line = [l.split() for l in open('file.txt').readlines()]
lis = []
for i in line:
  if i not in lis:
    lis.append(i)
  elif i == 1:
    lis.append(4)
f = open('file.txt', 'w+')
for i in lis:
  f.write(i)
f.close()

The file contents are first read and then split into a list in the list comprehension part. As the question asks to replace the repetition of 1 with 4, the loop checks for repetition of elements. The non repeated elements are straight-away added to the new list lis. If an element is already added in lis, and it again occurs in line, it means it is repeated. Now, if the repeated element is 1, append 4 to lis, and continue further. Finally, lis contains the required file content after replacement. The file.txt is over-written in the last lines with lis contents.

Swati Srivastava
  • 1,102
  • 1
  • 12
  • 18
  • 1
    Hi and welcome to stackoverflow, and thank you for answering. While this code might answer the question, can you consider adding some explanation for what the problem was you solved, and how you solved it? This will help future readers to understand your answer better and learn from it. – Plutian Jan 30 '20 at 11:17
  • 1
    Hi @Plutian, thanks for the welcome. I'd certainly take your suggestion and edit my answer right away! – Swati Srivastava Jan 30 '20 at 11:33
0

This will replace the last occurrence of the word

with open("1.txt",'r+') as file:
    a=list(file.read())
    print(a)
    word=input("Enter the Word want to replace")
    repl=input("Enter the word you want to enter")
    index_list=[]
    for i in range(len(a)):
        if word==a[i]:
            index_list.append(i)
    a[int(index_list[-1])]=repl

with open("1.txt",'w') as file:

    for i in a:
            file.write(i)
clubby789
  • 2,543
  • 4
  • 16
  • 32