正如標題所說,我用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 很好)
uj5u.com熱心網友回復:
所以這絕對是一個 Python 3.x 解決方案,但你說它很好,不知道它是否可以在 Python 2.x 中作業,但它很簡單,應該:
def file_overwrite(self, file, data):
with open(file, 'w') as file:
file.write('\n'.join(data))
而且您似乎還需要修復該data串列,因為它缺少幾個逗號。此外,這一切都在一個類中的事實有點奇怪,您對實體什么都不做,它們也可能是單獨的函式@classmethods或@staticmethods。您的其他功能也可以改進一些事情。例如,您不應該兩次打開檔案并計算其行數以讀取它。只需執行file.readlines()它將回傳所有行的串列:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334978.html
標籤:Python python-2.7
上一篇:PySparkreplace()函式不會用NULL值替換整數
下一篇:向量化條件列
