0

I need your help to write script python to remove last point in a text file.

I tried to remove a point from last sentence for first Without success.

f = open('text.txt','r')
last = f.readlines()
f.close()

f2 = open('text.txt','w')
last_line = last[-1:]
for i in range(0,(len(last)-1)):
if i == len(last)-1:
    f2.write(last[i].replace('.',' '))

f2.close
  • Please check the indentation of your code, the indentation in your question seems incorrect. – JeffUK Jun 17 '21 at 09:06

2 Answers2

0

Using this answer, you can do like this

def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)

f = open('text.txt','r')
content = f.read()
f.close()

f = open('text.txt','w')
f.write(rreplace(content, '.', ' ', 1))
f.close()
Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37
0

Here is a one-liner from this Answer:

result = new_string.join(text.rsplit(old_string, how_often))

Which would be in your case:

def remove_last_point(text):
    return "".join(text.rsplit(".", 1))
Einliterflasche
  • 473
  • 6
  • 18