我試圖在檔案的行之間放置星號,我試圖獲取每行末尾的句柄位置并開始寫入,但結果在檔案末尾插入星號。誰能解釋為什么會發生這種情況?
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)```
uj5u.com熱心網友回復:
您可以簡單地閱讀所有行并在它們之間添加 * ,如下所示:
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348473.html
上一篇:美麗的湯,只找一種圖案
下一篇:我需要將'jonathan-morón-16394669'轉換為'jonathan-morón-16394669'
