Dave Cameron
Dave Cameron

Reputation: 159

Python I/O both read and append (write)

I'm learning python and I saw this 'a+' mode for handling file streams. Why can't I do something like the code below to first read and check the file if it contains anything, and then write to it based on the evaluation?

with open('output.txt', 'a+') as logfile:
    textOfFile = logfile.read()
    if textOfFile != '':
        logfile.write("\r\nFile contains text")
    else:
        logfile.write("\r\nFile is empty")

The code above gave me the following error:

Traceback (most recent call last):
  File "C:/Python27/scripts/testfile.py", line 22, in <module>
    logfile.write("anything man")
IOError: [Errno 0] Error

Am I doing something wrong or is this not possible to do? What is then the point of 'a+'?

Upvotes: 1

Views: 1824

Answers (1)

Malik Brahimi
Malik Brahimi

Reputation: 16711

The a+ file mode appends to the file without overwriting it's current contents. In order to solve your problem, you'll need to first read the file's in reading mode which is the default like so:

text_r = open('text.txt').read()
text_a = open('text.txt', 'a+')

if text_r != '':
    text_a.write('\r\nFile contains text')
    text_a.close()

else:
    text_a.write('\r\nFile is empty')
    text_a.close()

Upvotes: 1

Related Questions