I have this homework which I need to define a function that does the following:
Write a function which given a text file object open in read and write mode and a string, inserts the text of the string in the file at the current read/write position. In other words, the function writes the string in the file without overwriting the rest of it. When exiting the function, the new read/write position has to be exactly at the end of the newly inserted string. The algorithm is simple; the function needs to:
- read the content of the file starting at the current read/write position
- write the given string at the same position step 1 started
- write the content read at step 1. at the position where step 2. ended
- reposition the read/write cursor at the same position step2. ended (and step 3. started).
I'm very confused by the steps 1-4 as to what I need do to, and the professor has been no help.
here is the code that I did, but I don't think the function follows the parameter given
def readWrite(file, string):
file.read()
file.seek(0)
file.write(string)
give_file = input("enter a file name: ")
give_string = input("enter a string: ")
try:
readFile = open(give_file, "a+")
file_content = readWrite(readFile, give_string)
except FileNotFoundError:
print("File does not exist")
exit(1)
The whole code should ask for a simple .txt
file, which it would take it and a string, and add it to the original file.
example: the file is Twinkle.txt
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
output:
twinkle.txt
1 Twinkle, twinkle, little bat!
2 How I wonder what you're at!
3 Up above the world you fly,
4 Like a teatray in the sky.