Home > Software engineering >  So I made a file editing program in python... and one of the functions isn't working right
So I made a file editing program in python... and one of the functions isn't working right

Time:10-26

As the title says, I made a file editing program with python.

Here is the code that I'm have a problem with:

#fileEditing.py

def fileError(file):
  raise OSError("file {} does not exist".format(file))

class AccessFile():
  def fileExists(self, file):
    import os
    return bool(os.path.exists(file))

  def filecreate(self, file):
    if not self.fileExists(file):
      with open(file, "w") as f:
        f.close()
    else: raise OSError("file {} already exists".format(file))

  def filedelete(self, file):
    import os
    if self.fileExists(file):
      os.remove(file)
    else: fileError(file)

  def fileread(self, file):
    #check if file exists
    if self.fileExists(file):
      #detect length of file
      with open(file, "r") as f:
        line = " "
        x = 0
        while line != "":
          line = f.readline()
          x  = 1
      #piece lines together in a list
      filelines = []
      with open(file, "r") as f:
        for i in range(x - 1):
          filelines.append(str(f.readline()))
      #return a tuple
      return tuple(filelines)
    else: fileError(file)

  def filewrite(self, file, line, text):
    ''' BUG: apparently this either overwrites the line its writing or appends
    to the line its writing... make up your mind!'''
    if self.fileExists(file):
      #get file contents
      filelines = list(self.fileread(file))
      #see if line parameter is out of range or not
      try:
        filelines[line] = text
      except IndexError:
        for i in range(line - len(filelines)):
          filelines.append("")
        filelines.append(str(text)   "\n")
      #apply changes
      with open(file, "w") as f:
        f.write("") #delete contents
      with open(file, "w") as f:
        for l in filelines:
          f.write(l)
    else: fileError(file)

  def fileoverwrite(self, file, data):
    #if there is no file to delete, it will make a new one
    try:
      self.filedelete(file)
    except:
      pass
    self.filecreate(file)
    x = 0
    for line in data:
      print(line)
      self.filewrite(file, x, line)
      x  = 1

accessfile = AccessFile()

The bug is in the filewrite(self, file, line, text) function. When called, it either writes a new line (which is what I want it to do), appends to the line its supposed to replace, or just doesn't write any lines at all.

Say I want to write a python file with this program:

#pytesting.py

from fileEditing import *

file = "/Users/ashton/Desktop/Atom/Python/FileEditing/FileManager.py"
data = [
"from fileEditing import *",
"",
"class FileEditing():",
"  def __init__(options, immutable_files):"
"    self.options, self.immutable_files = options, immutable_files",
"    ",
"  def prompt():",
"    "
""
"while True:",
"  pass"
]

accessfile.fileoverwrite(file, data)

When I run it, it makes a file with accessfile.fileoverwrite(file, data), like its supposed to.

But thats where things get whacky.

(FileManager.py below)

from fileEditing import *

class FileEditing():
  def __init__(options, immutable_files):    self.options, self.immutable_files = options, immutable_files
    
  def prompt():
    while True:

If you know how to fix the filewrite(self, file, line, text), please let me know.

(I use python 2.7 but python 3 is fine)

CodePudding user response:

So this is definitely a Python 3.x solution but you said that it is fine, don't know if it will work in Python 2.x but it is so simple it should:

def file_overwrite(self, file, data):
    with open(file, 'w') as file:
        file.write('\n'.join(data))

And you seemingly also need to fix that data list because it is missing a few commas. Also the fact that this is all in a class is a bit weird, you do nothing with the instance, they all might as well be separate functions or @classmethods or @staticmethods. Also several things could be improved with your other functions. For example you shouldn't open the file twice and count its lines to read it. Just do file.readlines() at it will return a list of all lines:

def fileread(self, file):
    if self.fileExists(file):
        with open(file) as file:
            return file.readlines()
    else: 
        fileError(file)

Then also import os once at the start of the file, you don't need to import it in every function where you use os, also:

with open(file, "w") as f:
    f.close()

f.close() is completely pointless because the context manger closes the file anyways and also there is mode "x" which is specifically made for file creation and will raise an error if the file already exists: https://www.w3schools.com/python/python_file_handling.asp

  • Related