0

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:

  1. read the content of the file starting at the current read/write position
  2. write the given string at the same position step 1 started
  3. write the content read at step 1. at the position where step 2. ended
  4. 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.
MMSS19
  • 125
  • 7
  • 2
    by steps 1 to 4? like the whole assignment? – Matiiss Apr 19 '21 at 21:30
  • @Matiiss its only the function. the main body just calls the function and numbers the lines (still figuring it out) – MMSS19 Apr 19 '21 at 21:31
  • also why are You exiting with 3 different exit codes? I will assume that is to keep track from which function the program exited – Matiiss Apr 19 '21 at 21:32
  • @Matiiss I think 2 functions need to be made into one.. but Im confused so idk how to do it – MMSS19 Apr 19 '21 at 21:32
  • 1
    @MMSS19 Maybe check out my answer to a similar question. I'm pretty sure it's what you are looking for. If it helps, don't forget to upvote :) https://stackoverflow.com/questions/66482152/can-you-write-to-the-middle-of-a-file-in-python/66482389#66482389 – Shihao Xu Apr 19 '21 at 21:33
  • @Matiiss I don't know. it filled the gaps. not so needed I think – MMSS19 Apr 19 '21 at 21:33
  • @Matiiss thank you I'll look at it – MMSS19 Apr 19 '21 at 21:34
  • Unrelated: An exit code of 0 usually means error-free execution – Pranav Hosangadi Apr 19 '21 at 21:35
  • Hint: start by defining a function and the arguments it will be passed… – martineau Apr 19 '21 at 22:07
  • @martineau I have defined a function. to read the file and append a string. I'm using seek(0,0) to get the string at the start of the file, but it keeps appending at the end? I will update the code in question section – MMSS19 Apr 19 '21 at 23:12
  • MMSS19:You can use an open file's [`tell()`](https://docs.python.org/3/library/io.html#io.IOBase.tell) method _at any time_ to determine its current position and you can use that information to later return to that position via `seek()`. That's all you need. Also, don't open the file in `"a+"` append mode, use "'r+'" to open it for reading and writing (without truncation). – martineau Apr 20 '21 at 00:34

2 Answers2

0

I have found the way to do it and here is the function:

def readWrite(file, string):
    if not file.readable():
        print("This file is not readable")
        file.close()
        return
    if not file.writable():
        print("This file is not writable")
        file.close()
        return
    initialPosition = file.tell()
    print(initialPosition)
    readContent = file.read()
    file.seek(initialPosition)
    file.write(string)
    secondPosition = file.tell()
    print(secondPosition)
    file.write(readContent)
    file.seek(secondPosition)

basically, this takes in the file and appends to it the file name and line numbering to each row. (the code for line numbering is in the main body below).

main body:

give_file = input("enter a file name: ")
try:
    openFile = open(give_file, "r+")
    position = openFile.tell()
except FileNotFoundError:
    print(give_file, " does not exist or could not open")
    exit(1)

counter = 0
for line in openFile:
    counter += 1
openFile.seek(position)
readWrite(openFile, give_file + "\n" + "\n")

spacing = 1
while spacing <= counter:
    readWrite(openFile, str(spacing) + " ")
    openFile.readline()
    spacing += 1

openFile.close()

there might be shorter more elegant solutions out there, but this one works for me

MMSS19
  • 125
  • 7
-1

I don't think I know the full answer, but I know it involves dealing with file streams. Look up the python docs for the TextIO object for that. file.write(content) in save_file deletes the existing content of the file in my experience. I believe you want to open the file in append mode at the bottom, for which the string parameter in open is 'a'

this link might help: https://www.guru99.com/reading-and-writing-files-in-python.html

Nathan Wolf
  • 336
  • 3
  • 12
  • [Your answer is in another castle: when is an answer not an answer?](//meta.stackexchange.com/q/225370/174780) – Pranav Hosangadi Apr 19 '21 at 21:33
  • this would better suit a comment but seeing that Your rep wouldn't allow that You should gain it by giving meaningful answers – Matiiss Apr 19 '21 at 21:33
  • I see what you mean that this answer is too brief, but the link isn't a tutorial that does the heavy lifting for me, the link is just because I wasn't about to burden my answer's concision with a full explanation of python's `open` method – Nathan Wolf Apr 19 '21 at 21:43