English 中文(简体)
如何以列表形式装入文件, 并将其放入与其装入的类别不同的类别
原标题:how to load a file as a list and place it in a different class to the one its loading in
class Tasks(object):
    def __init__(self, container=None):
        if container is None:
            container = []
        self.container = container


    def add(self,name,date,priority):
        self.container.append([name,date,priority])

    def __str__(self):
        return str(self.container)

    def __repr__(self):
        return str(self.container)

    def __getitem__(self, key):
        return Tasks(self.container[key])

    def __len__(self):
        return len(self.container)


class management(Tasks):
    def save(self):
        outfile = open ("tasks.txt","w")
        outfile.write(("
".join(map(lambda x: str(x), task))))

        print task
        outfile.close ()
    def load(self):
        load_file = open("tasks.txt","r")
        task = load_file.readlines()
        print task
        #this line is the attempt to convert back into the original format
        Tasks(add(task))




task = Tasks()        
if __name__== "__main__":

    p = management(Tasks)

    #task.add("birthday","27092012","high")
    #task.add("christmas","20062000","medium")
    #task.add("easter","26011992","low")
    print task

    #print len(task)
    #p.save()
    p.load()


    print "test",task
    print len(task)

我的代码的最终目的 是要产生一个任务经理( 做列表)

上面的代码产生一个列表[名称、日期、优先,然后保存在名为任务.txt - 的文本文件中,只要我意识到这一点是完全有效的(只要我对 p.load 进行评论)。

然而... 负载函数会加载文件, 但我需要能够打印列表 它载载载的打印任务, 就像我评论 p.load () 时一样 。

这将让我最终能够删除任务等等。

提前感谢

我为这个坏问题道歉 我不知道该怎么在1线上说

edit: I thought about pickling which would preserve the list format, but i dont think it would solve my problem of being able to pass the arguments back into the Tasks() class in order to be able to print them as print task

edit 2 the load function now reads

 def load(self):
     with open("tasks.txt", "r") as load_file:
         tasks = [ast.literal_eval(ln) for ln in load_file]
     print tasks
     for t in tasks:
         todo.add(t)

obviously (or at least I think ) I get the error NameError: global name todo is not defined I have tried with task.add(t) and get TypeError: add() takes exactly 4 arguments (2 given)

我还尝试过任务.add(t), 并得到了错误 TypeError: 必须将无约束方法添加 () 调用任务实例作为第一个参数( 而不是列表实例)

我显然不明白代码, 你能澄清一下吗,谢谢。

edit 3 while True: menu_choice = int(input("Select a number from the menu"))

try:
    if menu_choice == 1:

        task = raw_input ("task")
        date = raw_input ("date")
        priority = raw_input ("priority")
        tasks = Tasks([(task,date,priority)])
        print tasks


    elif menu_choice == 2:
        print tasks
    elif menu_choice == 3:
        tasks.save()
    elif menu_choice == 4:
        tasks.load()
except:
    print sys.exc_info()

而不是附加任何想法? 菜单选择 2,3,不起作用, 因为任务不是全球性定义,

最佳回答

尝试一种不同、 更多的波音方法。 这并不是一个答案, 而是一个选项。 经过三次编辑, 以考虑到对新功能的一些要求 。

import pickle

class TasksError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class Task(object):
    def __init__(self, task = () ):
        if task ==():
            raise TasksError( Empty task. )
        self.name = task[0]
        self.date = task[1]
        self.priority = task[2]

    def __str__(self):
        output =    Name: %s
Date: %s
Priority: %s
    % ( self.name,
        self.date,
        self.priority )
        return output

class Tasks(object):
    def __init__(self, container = []):
        self.container = [ Task(todo) for todo in container ]

    def find_by_priority(self, priority =  high ):
        # example method to seek and print high priority tasks
        # using this example, you will be able to conduct many
        # types of searches
        results = [ task
                   for task in self.container
                   if task.priority == priority ]
        return results

    def sort_by_date(self):
        # example method of how to sort, again, many other
        # ways of sorting can be implemented, this is just
        # to demonstrate the principle
        # for more info on sorting,
        # visit:  http://wiki.python.org/moin/HowTo/Sorting
        self.container = sorted(self.container,
                                key=lambda task: task.date)

    def add(self, task):
        if task ==   :
            raise TasksError( Empty task )
        self.container.append( Task(task) )

    def save(self):
        try:
            output = open( tasks.pkl ,  wb )
            pickle.dump(self.container, output)
            output.close()
        except:
            raise TasksError( Failed to save. )

    def load(self):
        try:
            pkl_file = open( tasks.pkl ,  rb )
            self.container = pickle.load(pkl_file)
            pkl_file.close()
        except:
            raise TasksError( Failed to load )

    def __str__(self):
        output =  
 .join( [ str(todo) for todo in self.container ] )
        return output

if __name__== "__main__":
    divider =  -  * 30 +  
 

    tasks = Tasks( [("birthday","20121111","high"),
                    ("christmas","20121225","medium"),
                    ("easter","20120405","low")] )
    print  Three original tasks:
 
    print tasks # prints out three tasks
    print divider

    tasks.add( ("new-task","20120320","high") )
    print  Three original plus one new task:
 
    print tasks # prints out four tasks
    print divider

    tasks.save() # pickles the task list and saves to disk

    tasks = Tasks( container = [] ) # creates a new, empty task list
    print  Empty task list:
 
    print tasks # prints out empty list
    print divider

    tasks.load() # loads the pickled list
    print  The four pickled tasks, reloaded:
 
    print tasks # prints out four tasks
    print divider

    while True:
        print divider,    Make your selection:
1. Add new task
2. Print all tasks
3. Save tasks
4. Load tasks from disk
5. Find high priority tasks
6. Sort by date
<ENTER> to quit
   
        try:
            menu_choice = int(input("Select a number from the menu: "))
        except:
            print  Goodbye! 
            break

        if menu_choice == 1:
            # note: no error checking here
            # even an empty input is accepted
            task = raw_input (">>> Task: ")
            date = raw_input (">>> Date as string YYYYMMDD: ")
            priority = raw_input (">>> Priority: ")
            todo = (task, date, priority)
            # note that here you should add a task
            # your method created a NEW task list
            # and replaced the old one
            tasks.add( todo )
            print tasks
        elif menu_choice == 2:
            print divider,  Printing all tasks 
            print tasks
        elif menu_choice == 3:
            print divider,  Saving all tasks 
            tasks.save()
        elif menu_choice == 4:
            print divider,  Loading tasks from disk 
            tasks.load()
        elif menu_choice == 5:
            print divider,  Finding tasks by priority 
            results = tasks.find_by_priority(priority= high )
            for result in results: print result
        elif menu_choice == 6:
            print divider,  Sorting by date 
            tasks.sort_by_date()
            print tasks

备注: 这是为展示您想要执行的许多特征和展示如何正确使用对象导向设计使您能够包罗每一项任务和任务清单并轻松地加以操作而制作的代码。 它也展示了使用泡菜作为原始问题中使用的文本文件执行的“ 音调” 替代物。 它也显示了按字段搜索和排序, 采用了两种简单的方法 。

如果您对这个项目是认真的, 您需要查看适当的数据库, 如 < a href=" http://docs. python. org/library/ sqlite3. html" rel=“ nofollow” >SQLite , 这样的人将无法用手可靠地执行搜索、 排序、 更新、 添加和删除记录。

问题回答

假设您的名称、任务和优先事项是简单的 Python 对象,您可以用 ast.literal_eval 装入:

with open("tasks.txt", "r") as load_file:
    # no need for readlines, just loop over the file!
    tasks = [ast.literal_eval(ln) for ln in load_file]

然后绕过 tasks 来将对象放入 Tasks 对象中。 请注意, Tasks (add( task)) 将无法工作。 您需要有一个类型为 Tasks 的对象, 传递给 load (lets call it todo ), 并进行操作 。

for t in tasks:
    todo.add(t)

Btw., 您不需要 < code> management 类。 两种独立的功能都很好 。 < a href="http:// dirtspone. org/2004/12/ python- is- not- java. html" rel = "nofollow" > Python 不是 Java





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...