Как заставить режим Read plus (r +) работать в python 3? - PullRequest
1 голос
/ 26 марта 2019

Я пытаюсь добавить текст в режиме r + к уже существующему ранее созданному файлу, но я не знаю, почему он не работает. Вот мой код:

#Here i'm creating the file 'task5_file'

 task5_file = open('task5_file.txt', 'w+')
 task5_file.write("Line---1\nLine---2\nLine---3\nLine---4\nLine---5\nLine---6\nLine---7\nLine---8\nLine---9\nLine--10\n")
 task5_file.seek(0)
 print("Before:\n"+ task5_file.read()+"\n")
 task5_file.close()

#Next i'm trying to append text 5 times and add it every 18 characters. (starting the first loop, item is 1 if using range(1,5), seek will be set to 18, 36, 54, 72) 

 task5_file=open('task5_file.txt','r+')

 for item in range(1,5):
     task5_file.seek(item*18)
     task5_file.write("append#"+str(item)+"\n")

 print("After:\n+task5_file.read())

Вот что я получаю:

Before:
Line---1
Line---2
Line---3
Line---4
Line---5
Line---6
Line---7
Line---8
Line---9
Line--10

After:
Line--10

1 Ответ

0 голосов
/ 14 апреля 2019
# [ ] complete the task
# Provided Code creates and populates task5_file.txt
task5_file = open('task5_file.txt', 'w+')
task5_file.write("Line---1\nLine---2\nLine---3\nLine---4\nLine---5\nLine-- 
-6\nLine---7\nLine---8\nLine---9\nLine--10\n")
task5_file.seek(0)
print("Before:\n"+ task5_file.read()+"\n")
task5_file.close()

# [ ] code here

task5_file = open('task5_file.txt','r+')

for item in range(1,5):

    task5_file.write("append#" + str(item) + "\n")
    task5_file.seek(item*18)

task5_file.seek(0) #here is the important
print(task5_file.read(),"\n")
...