2

I want to read and write files multiple times.But the way is failed,it only writes the last modified content rather than all modified contents.

The incorrect program

def openfile():
    txt = open("test.txt", "r")
    contents = txt.readlines()
    txt.close()
    return contents

def write_file(contents,f):
    old_contents = openfile()
    old_contents.insert(1,contents)
    contents = "".join(old_contents )
    f.write(contents)
    f.close()

text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)

text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)**

Worry Output

test2

My hope output

test1
test2
M.Mark
  • 63
  • 2
  • 13

4 Answers4

1

This is too much of code for the File Open and Write, You can just use this following lines to append the text in your file

def FileSave(filename,content):
    with open(filename, "a") as myfile:
        myfile.write(content)

FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")

Here, when we using this line open(filename, "a"), the a indicates the appending the file, that means allow to insert extra data to the existing file

K.Suthagar
  • 2,226
  • 1
  • 16
  • 28
1

as stated in the python doc you need to open your file with mode='a' if you want to append to existing data; mode='w' simply overwrites:

with open(file='_test.txt', mode='a') as file:
    file.write('test')

(if you are using python 2, change the variable name file above to something else; in python 2 file is a keyword).

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1

The reason for your "Worry Output" is that you re-open "test.txt" in read mode inside openfile after you've already opened it in write mode outside the functions. When you open a file in write mode it gets truncated, i.e., the file pointer is positioned to the start of the file and the current contents of the file are discarded. So when you call openfile inside write_file the file is empty, and thus openfile returns an empty list.

Here's a repaired version of your code. We use try... except in openfile so we can return an empty list if the file doesn't exist.

def openfile(fname):
    try:
        f = open(fname, "r")
        contents = f.readlines()
        f.close()
        return contents
    except FileNotFoundError:
        return []

def write_file(contents, fname):
    old_contents = openfile(fname)
    old_contents.insert(1,contents)
    contents = "".join(old_contents)
    f = open(fname, "w")
    f.write(contents)
    f.close()

contents= "test1 \n"
write_file(contents, "test.txt")

contents = "test2 \n"
write_file(contents, "test.txt")

And here are the contents of "test.txt" after running that code:

test1 
test2 

Actually, it's better to use with when opening files:

def openfile(fname):
    try:
        with open(fname, "r") as f:
            contents = f.readlines()
        return contents
    except FileNotFoundError:
        return []

def write_file(contents, fname):
    old_contents = openfile(fname)
    old_contents.insert(1,contents)
    contents = "".join(old_contents)
    with open(fname, "w") as f:
        f.write(contents)

However, a much better way to do this is to simply open the file in append mode as hiro protagonist and K.Suthagar have already shown. But I figured it was a good idea to explain why your current code didn't do what you expected it to do.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
1

text1 = open("test.txt","w")

It is because above code resets the content. "w" is to override the file content.

Below code should explain you where you went wrong-

def openfile():
    txt = open("test.txt", "r")
    contents = txt.readlines()
    print "Openfile method- Contents: "+str(contents)
    txt.close()
    return contents

def write_file(contents,f):
    print "WriteFile method- Content received: "+str(contents)
    old_contents = openfile()
    print "Writefile method- Old content read from file: "+str(old_contents)
    old_contents.insert(1,contents)
    print "Writefile method- Old content after insertion: "+str(old_contents)
    contents = "".join(old_contents )
    print "WriteFile method- Content to write: "+str(contents)
    f.write(contents)
    f.close()

text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)

text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)

As mentioned, use "a" to append to file.

Swapnil Patel
  • 757
  • 1
  • 7
  • 9