I am trying to put stars between lines of a file, I tried to get the position of handle at end of each line and start writing, but the result inserts stars at the end of the file. can anyone explain why this happens?
with open('exercise3.txt','r ') as file:
lines = file.readlines()
file.seek(0)
for i in range(len(lines)-1):
line = file.readline()
oldpos = file.tell()
file.write('\n' 20*'*' '\n')
file.seek(oldpos)```
CodePudding user response:
You can simply read all lines and add * between them like this:
file = open("file.txt", "r")
lines = file.readlines() //This will return a list of lines
newFileLines = []
//Go trough indexes of lines if index%2 != 0: //Check if its even or odd index(if odd, add the line, if even, add stars -> first line, will be added, second index, will add "*" adn the next line and so on)
for index in range(len(lines)):
newFileLines.append(20*"*" "\n")
newFileLines.append(lines[index])
file.close()
file = open("newFile.txt", "w")
file.writelines(newFileLines)
file.close()