Last active
January 3, 2016 00:59
-
-
Save mewm/8386292 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Create, read, update, append and delete file test | |
""" | |
import sys, os | |
class FileOperation(): | |
def __init__(self, file): | |
self.file = file; | |
# Create file | |
def create_file(self): | |
try: | |
self.f = open(self.file, 'w') | |
finally: | |
self.f.close() | |
# Delete file | |
def delete_file(self): | |
os.remove(self.file) | |
# Read file | |
def read_file(self): | |
try: | |
self.f = open(self.file, 'r') | |
r = self.f.read() | |
finally: | |
self.f.close() | |
print(r) | |
# Write to file | |
def write_to_file(self, content): | |
try: | |
self.f = open(self.file, 'w') | |
self.f.write(content) | |
finally: | |
self.f.close() | |
# Append to file | |
def append_to_file(self, content): | |
try: | |
self.f = open(self.file, 'a') | |
self.f.write(content) | |
finally: | |
self.f.close() | |
# Make writeable | |
def make_writable(self): | |
try: | |
os.chmod(self.file, 655) | |
finally: | |
print '%s is now writable' % self.file | |
class FileCli(): | |
def __init__(self): | |
# Init vars | |
if len(sys.argv) > 1: | |
self.action = sys.argv[1] | |
self.file = sys.argv[2] | |
# Init message | |
print "Working with: %s" % self.file | |
print "Action: %s" % self.action | |
# Init script | |
if len(sys.argv) > 1: | |
operation = FileOperation(self.file) | |
if self.action == 'create': | |
operation.create_file() | |
elif self.action == 'delete': | |
operation.delete_file() | |
elif self.action == 'read': | |
operation.read_file() | |
elif self.action == 'write': | |
operation.write_to_file(sys.argv[3]) | |
elif self.action == 'append': | |
operation.append_to_file(sys.argv[3]) | |
elif self.action == 'writable': | |
operation.make_writable() | |
else: | |
self.help() | |
else: | |
self.help() | |
else: | |
self.help() | |
def help(self): | |
print '' | |
print '---------- help ----------' | |
print 'Functions: create, delete, read, write, append, writable.' | |
print 'Usage: $ python files.py [function] [filepath] [content (write, append)]' | |
print '--------------------------' | |
print '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment