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?
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?
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
You can replace by position using this solution
s = list("1 2 3 1 5")
s[6]="4";
print("".join(s))
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
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.
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)