文件创建和目录验证类
在阅读了关于在python下创建文件的一些文本之后,我决定创建这个类,它在一个目录上创建一个新文件,并且在该文件已经存在的情况下在另一个目录上创建一个备份(并且如果它早于x小时)
我打开这个问题的主要原因是要知道,如果这是一个正确的方式来写一个类使用尝试/除非正确,因为实际上我对使用尝试/除了而不是/ elses的偏好有点困惑。
贝娄,工作的例子:
import os
import datetime
class CreateXML():
def __init__(self, path, filename):
self.path = path
self.bkp_path = "%sbackup" % path
self.filename = filename
self.bkp_file = "%s.previous" % filename
self.create_check = datetime.datetime.now()-datetime.timedelta(hours=-8)
@staticmethod
def create_dir(path):
try:
os.makedirs(path)
return True
except:
return False
@staticmethod
def file_check(file):
try:
open(file)
return True
except:
return False
def create_file(self, target_dir, target_file):
try:
target = "%s%s" % (target_dir, target_file)
open(target, 'w')
except:
return False
def start_creation(self):
try:
# Check if file exists
if self.file_check("%s%s" % (self.path, self.filename)):
self.create_dir(self.bkp_path)
creation = os.path.getmtime("%s%s" % (self.path, self.filename))
fcdata = datetime.datetime.fromtimestamp(creation)
# File exists and its older than 8 hours
if fcdata < self.create_check:
bkp_file_path = "%s%s " % (self.bkp_path, self.bkp_file)
new_file_path = "%s%s " % (self.path, self.filename)
# If backup file exists, erase current backup file
# Move existing file to backup and create new file.
if self.file_check("%s%s" % (self.bkp_path, self.bkp_file)):
os.remove(bkp_file_path)
os.rename(new_file_path, bkp_file_path)
self.create_file(self.bkp_path, self.bkp_file)
#No backup file, create new one.
else:
self.create_file(self.bkp_path, self.bkp_file)
else:
# Fresh creation
self.create_dir(self.path)
self.create_file(self.path, self.filename)
except OSError, e:
print e
if __name__ == '__main__':
path = 'c:tempdata'
filename = 'somefile.txt'
cx = CreateXML(path, filename)
cx.start_creation()
所以,基本上这里真正的问题是:
- 使用上面的例子,try / except的用法是正确的吗?
- 使用try /执行验证是正确的,除了检查文件或目录是否已经存在? 而是使用像这样的简化版本:
import os
# Simple method of doing it
path = 'c:tempdata'
filename = 'somefile.txt'
bkp_path = 'c:tempdatabackup'
bkp_file = 'somefile.txt.bkp'
new_file_path = "%s%s" % (path, filename)
bkp_file_path = "%s%s" % (bkp_path, bkp_file)
if not os.path.exists(path):
print "create path"
os.makedirs(bkp_path)
if not os.path.isfile(new_file_path):
print "create new file"
open(new_file_path, 'w')
else:
print"file exists, moving to backup folder"
#check if backup file exists
if not os.path.isfile(bkp_file_path):
print "New backup file created"
open(bkp_file_path, 'w')
else:
print "backup exists, removing backup, backup the current, and creating newfile"
os.remove(bkp_file_path)
os.rename(new_file_path, bkp_file_path)
open(bkp_file_path, 'w')
- 如果try / except的用法是正确的,那么如果可以编写一个简短版本的文件,它的recomended会写一个大类来创建一个文件?
请不要关闭这个步骤,因为我对什么是“最正确的pythonic做法”感到困惑。
提前致谢。
链接地址: http://www.djcxy.com/p/54677.html