I was making this file editing class (writing to a file, reading a file etc.) in Python and was just looking for any feedback.
Note: I've been thinking about removing the file_name
property and requiring file name on each method call.
import os
class EditFile:
"""
format: <object_name> = EditFile(<file_name>)
"""
# constructor
def __init__(self, file_name):
self.file_name = file_name # can be changed at any time
# string version
def __repr__(self):
return "<object_name> = EditFile(<file_name>)"
# methods
def write(self, text): # writes text in a file
try:
f = open(self.file_name, "w") # opens file & selects WRITE mode also creates a new file if it doesnt exist
f.write(str(text))
finally:
f.close()
def append(self, text): # appends text to a file
try:
f = open(self.file_name, "a") # opens file & selects APPEND mode
f.write(text)
finally:
f.close()
@property
def read(self): # reads the file
try:
f = open(self.file_name, "r") # opens file & selects READ mode
content = f.read() # saves content of the file into content variable
finally:
f.close()
return content # returns content of the file
def read_bytes(self, number_of_bytes = 0): # reads certain amount of bytes
try:
int(number_of_bytes)
if number_of_bytes == 0: # checks if its default
f = open(self.file_name, "rb")
content = f.read()
return content
elif number_of_bytes >= 1: # checks if number of bytes is a valid number
f = open(self.file_name, "rb")
content = f.read(number_of_bytes)
return content
else:
return "error" # returns "error" if input is invalid
except ValueError:
return "value error"
finally:
f.close()
def write_bytes(self, text): # writes in bytes
try:
f = open(self.file_name, "wb") # selects WRITE BYTES mode
f.write(str(text))
finally:
f.close()
@property
def clear(self): # clears a file
try:
f = open(self.file_name, "w") # opens file and selects WRITE mode
f.write("") # sets file content to none
finally:
f.close()
@property
def delete(self): # deletes current file
try:
os.remove(self.file_name) # tries to delete file
except OSError:
return "error" # returns "error" if an error occurs (eg file doesnt exist)
# example program using most of the methods
file = EditFile("editme.txt")
file.write(str(input("Text:\n")))
print(file.read)
file.clear
file.delete
# editing file: editme2.txt
file.file_name = "editme2.txt"
file.write(str(input("Text:\n")))
print(file.read_bytes(5))
file.delete