Is this needed?

class Test:
    def __init__(self, f):
        self.f = open(f)

    def __del__(self):
        try:
            self.f.close()
        except:
            pass

Also, how can i open a file, and have it in append mode. However, if the file doesn't exist, python creates it?

Recommended Answers

All 6 Replies

Like they say: "If nothing else succeeds, read the manual".

7.2. Reading and Writing Files
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

>>> f = open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

well i did. I use "a" for appending.

tried "aw" "bw" "wa" none seems to be working.

Is this needed?

class Test:
    def __init__(self, f):
        self.f = open(f)

    def __del__(self):
        try:
            self.f.close()
        except:
            pass

Not absolutely needed, but that's a way to do things, with magic methods.
This way, you can do:

a = Test("myfile.txt")
del a

Or of course you can do this, (which is how I would do it)

with open("myfile.txt") as fileio:
    info = fileio.readlines()

But my program requires an instance of a class to open a file. So shouldn't i close it before it's deleted or is the file deleted with the instance?

Funny manual instructions work for me:

>>> open('out.txt','w').write('old balabala\n')
>>> open('out.txt','a').write('new balabala\n')
>>> print open('out.txt','r').read()
old balabala
new balabala

>>>

Is this needed?

class Test:
    def __init__(self, f):
        self.f = open(f)

    def __del__(self):
        try:
            self.f.close()
        except:
            pass

Also, how can i open a file, and have it in append mode. However, if the file doesn't exist, python creates it?

Tha class approach is somewhat awkward, but you could use it like that:

class FileTest:
    def __init__(self, fname, *args):
        self.f = open(fname, *args)

    def __del__(self):
        try:
            # close file on instance deletion
            self.f.close()
        except:
            pass


fap = FileTest("MyFile1.txt", "a")
fap.f.write("Line one\n")
fap.f.write("Line two\n")
del fap  # closes file

# this won't work since fap is deleted
#fap.f.write("Line three\n")

fin = FileTest("MyFile1.txt", "r")
s = fin.f.read()
print( s )
del fin

'''
Line one
Line two
'''

The approach jcao219 would use is much better.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.