如何使Read Plus(r +)模式在python 3中工作?

时间:2019-03-26 19:29:11

标签: python python-3.x readfile

我正在尝试使用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 :(得分:0)

# [ ] 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")