Menu

Beanzilla

Never give up, Never surrender

Python Essentials: Advanced File Writing and Reading with your own class

In advFiler.py

class filer:
    """
    Allows simple file interactions with ease...
    """
    def __init__(self, filename='Oops.txt'):
        self.file = filename
    
    def __str__(self):
        return self.file
    
    def filename(self, filename2):
        """
        Sets a new File to be edited
        """
        self.file = filename2
    
    def advAppend(self, content):
        """
        Advanced Append: (Write onto the end of the file!)
        advAppend('filename.txt', 'content')
        """
        with open(self.file, 'a') as fs:
            fs.write(content)
    
    def advWrite(self, content):
        """
        Advanced Write: (Rewrite Entire File with given content!)
        advWrite('filename.txt', 'new_content')
        """
        with open(self.file, 'w') as fs:
            fs.write(content)
    
    def advRead(self):
        """
        Advanced Read: (Reads in the entire file and returns it!)
        """
        with open(self.file, 'r') as fs:
            return fs.read()

if __name__ == '__main__':
    myFiler = filer('EXText.txt')
    myFiler.advWrite('Welcome to filer!\n')
    print(myFiler.advRead())
    myFiler.advAppend('Version: 0.0.1\n')
    print(myFiler.advRead())
else:
    print('Loaded: advFiler.py')

In our main python file (I.E. advUse.py)

from __future__ import print_function
from advFiler import filer


print("Writing Basic Docs for advFiler.py...")
myFiler = filer('advFilerDOCS.txt')
myFiler.advWrite('Welcome to Advanced Filer:\n')
myFiler.advAppend("Use filer.filename('newFilename') to set a new file to write/read/append\n")
myFiler.advAppend("Use filer.advRead() to read the file also being written/Appended\n")
myFiler.advAppend("Use filer.advWrite('ContentForFile') to rewrite the entire file\n")
myFiler.advAppend("If you've forgot what file your writing/reading/appending just print(filervarialbe)\n")
print(myFiler)
myFiler.advAppend("Use filer.advAppend('ContentForFile') to add onto the end of the file\n")
myFiler.advAppend("If you forgot to assign a filename on initialization by default 'Oops.txt' is used\n")
print("Basic Docs can now be found for advFiler.py, Filename is advFilerDOCS.txt\n")
print(myFiler.advRead())

Enjoy the Docs and a easy way to write and append to a single file.

Written by Bzy on Thursday December 6, 2018

Permalink -

« Python Essentials: Print and all that fun stuff - BZ & BZ BBS »

Related content