所以我在 python... 中制作了一个文件编辑程序,其中一个功能无法正常工作

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

正如标题所说,我用python做了一个文件编辑程序。

这是我遇到问题的代码:

#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()

错误在 filewrite(self, file, line, text) 函数中。调用时,它要么写一个新行(这是我想要它做的),附加到它应该替换的行,要么根本不写任何行。

假设我想用这个程序写一个 python 文件:

#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)

当我 运行 它时,它会生成一个 accessfile.fileoverwrite(file, data) 的文件,就像它应该的那样。

但这就是事情变得古怪的地方。

(下FileManager.py)

from fileEditing import *

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

如果您知道如何修复 filewrite(self, file, line, text),请告诉我。

(我使用 python 2.7 但 python 3 没问题)

所以这绝对是一个 Python 3.x 解决方案但是你说它很好,不知道它是否适用于 Python 2.x 但是它很简单,应该:

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

而且您似乎还需要修复 data 列表,因为它缺少几个逗号。此外,这一切都在 class 中这一事实有点奇怪,您对实例不做任何事情,它们也可能都是单独的函数或 @classmethods@staticmethods。您的其他功能也可以改进几件事。例如,您不应该打开文件两次并计算其行数来阅读它。只需执行 file.readlines() 即可 return 所有行的列表:

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

然后 import os 在文件的开头一次,您不需要在每个使用 os 的函数中导入它,还有:

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

f.close() 完全没有意义,因为上下文管理器无论如何都会关闭文件,而且还有模式 "x" 专门用于创建文件,如果文件已经存在,则会引发错误:https://www.w3schools.com/python/python_file_handling.asp