[Tutor] Retrieving information from a plain text file(WinXP/py2.6.2/Beginner)

Katt the_only_katala at verizon.net
Fri Nov 6 03:02:14 CET 2009


>> Hello all,
>>
>> Thank you all for your help.  I appreciate it alot.
>>
>> I have been trying to work with file IO alot recently and would like to
>> improve my little program so that I no longer use a hard coded list, but 
>> a
>> text file that I can edit easily.
>>
>> The text file is three lines long and looks exactly like this:
>>
>> Reminder1,2009_10_28
>> Reminder2,2009_11_01
>> Reminder3,2009_11_15
>>
>> My program consists of the following code:
>> ============
>> #]------------------[import modules]------------------[
>> from time import strftime, mktime, localtime
>> from WConio import textcolor
>> #]--------------------------------------------------------[
>> #]------------------[define functions]------------------[
>> def read_reminders():
>>   print "\nReading text file into program: reminders.txt"
>>   text_file = open("reminders.txt","r")
>>   reminders = [line.strip().split("'") for line in text_file]
>>   text_file.close()
>>   print reminders
>> #
>> def get_computer_date():
>>   #Get today's date from the computer
>>   todays_date = strftime("%Y_%m_%d")
>>   return todays_date
>> #
>> def color_print(strings):
>>   #Change the text color in the WinXP dos shell
>>   #The way to use:
>>   #color_print([("string",color number),\
>>   #(str(variable),color number),(etc)])
>>   for string in strings:
>>       textcolor(string[1])
>>       print string[0],
>> #
>> def change_to_julian(reminder_date):
>>   #Receives the year, month, and day
>>   #in the form of a single string (2009_10_15)
>>   #and changes it into three different int
>>   #variables.  Then take those three variables
>>   #and append six zeros and change into a
>>   #julian date.
>>   date = []
>>   date = reminder_date.split("_")
>>   year = int(date[0])
>>   month = int(date[1])
>>   day = int(date[2])
>>   timetuple = (year, month, day) + ( (0,) * 6 )
>>   unixtime = mktime(timetuple)
>>   timetuple = localtime(unixtime)
>>   print days_left(timetuple[7])
>>   # [7] is the number of julian-date field of
>>   #the unixtime tuple.
>>   return days_left(timetuple[7])
>> #
>> def days_left(julian_date):
>>   #This function calculates the days left
>>   #until a reminder.  If the days left are
>>   #greater than 0 it will print normally.
>>   #If it is -1 then it will print differently.
>>   #Also if it is greater than -1 it will print
>>   #yet again differently.
>>   days_until_reminder = julian_date - localtime().tm_yday
>>   if days_until_reminder > 0:
>>       color_print ([("There are",7),(str(days_until_reminder),4),("days
>> left until this reminder.",7),("\n",7)])
>>   elif days_until_reminder == -1:
>>       color_print ([("\tYou have missed this reminder
>> by",4),(str(days_until_reminder*-1),4),("day!",4),("\n",7)])
>>       color_print [("
>>  ------------------------------------------------------------------------",4),("\n",7)])
>>   else:
>>       color_print ([("\tYou have missed this reminder
>> by",4),(str(days_until_reminder*-1),4),("days!",4),("\n",7)])
>>       color_print [("
>>  ------------------------------------------------------------------------",4),("\n",7)])
>> print
>> #
>> def compare_reminders(todays_date):
>>   #This function compares the reminders
>>   #to the computer date.
>>   #It has three different paths:
>>   # 1.Matches today's date
>>   # 2.The reminder date has already
>>   #  passed by
>>   # 3.The reminder date is yet to
>>   #  come.
>>   #After determining which it is it will
>>   #access the change_to_julian and
>>   #days_left functions.
>>   #reminders.sort()
>>   color_print ([("
>> [-------------------------------------------------------------------------]",4),("\n",7)])
>>   index = 0
>>   while index < len(reminders):
>>       if todays_date == reminders[index][1]:
>>           print
>>           color_print [("
>>  ------------------------------------------------------------------------",4),("\n",7)])
>>           print "Today's reminder is:
>> ",reminders[index][0],"on",reminders[index][1]
>>           color_print ([("\t\tTake care of this reminder
>> immediately",2),("\n",7)])
>>       elif todays_date > reminders[index][1]:
>>           print
>>           print "Whoops, you missed the following
>> reminder.",reminders[index][0],"on",reminders[index][1]
>>           change_to_julian(reminders[index][1])
>>       else:
>>           print
>>           print "Your upcoming reminders are:
>> ",reminders[index][0],"on",reminders[index][1]
>>           change_to_julian(reminders[index][1])
>>       index = index + 1
>>   color_print ([("
>> [-------------------------------------------------------------------------]",4),("\n",7)])
>> #]--------------------------------------------------------[
>> #]-------------------[Main Program]-------------------[
>> read_reminders()
>> print reminders
>> compare_reminders(get_computer_date())
>> pause_it = raw_input("Press a key to end: ")
>> #]--------------------------------------------------------[
>> ============
>> Could someone explain to me why my read_reminders function retrieves the
>> information, but cannot process that information?
>>
>> When I try and run the program I get the following error message:
>> ============
>> Reading text file into program: reminders.txt
>> [['Reminder1,2010_10_15'], ['Reminder2,2010_11_01'],
>> ['Reminder3,2010_11_15']]
>> Traceback (most recent call last):
>>   File "reminders.py", line 182, in <module>
>>       print reminders
>> NameError: name 'reminders' is not defined
>> ============
>>
>> Thanks in advance for your help,
>>
>> Katt
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>
> #]-------------------[Main Program]-------------------[
> reminders = read_reminders()

This is the item that I was forgeting.  Originally I tried to use the 
"return" in my function, but left out what I was returning.  However if I 
did not notice this one line I would have continued to be stuck.  I guess I 
thought all you would have to do is call the function and it would know to 
make the return information into a global list.

===================================================
> It appears you did not return the list of reminders that you extracted
> in the "read_reminders" function, but simply printed them from inside
> that function.

Yes, originally I did this to find out how python would read the 
information.  Kind of an error check type thing.

> called "reminders", you  should be able to access the list in your
> global namespace.

If I hadn't paid attention to the end of Vince's post I would have not 
understood this as I am unfamiliar with some of the vocabulary (i.e.: global 
namespace).

> Also, on a side note, you can greatly improve the readability of your
> code by using the triple-quote style for multi-line docstrings inside
> functions (rather than the hash comment marks). I tend to use hash
> marks for one-line/inline comments, since they can really become an
> eyesore (at least IMHO) when used too liberally.
>
> Also, Python's whitespace and code formatting conventions can handle a
> lot of the "documentation" for you. For instance,  module imports are
> typically always performed at the top of a script, so it's reasonable
> to expect that others reading your code will understand you're
> importing some modules.
>
> Much of this spelled out in PEP's 8 (style guide) and 257 (doc strings):
>
> http://www.python.org/dev/peps/pep-0008/
> http://www.python.org/dev/peps/pep-0257/

I will make sure to check these out soon so that my comments are more 
readable.

==============================================

> (Looks like maybe you hijacked another thread, instead of just creating
> a new message, with new topic, for the list)

Sorry, about that.  I got lazy and just replied to a tutor message I had in 
my inbox.  Will make sure not to let that happen again.

> Once you get that sorted out, another bug that's already apparent is
> that you're trying to split the line on quotes, when it uses commas
> between fields on each line.

Missed that one.  Once I changed this everything clicked into place.

 Thank you Alan G.,Vince S., Serdar T., and Dave A. for your help.  I don't 
think I woud have got this on my own.  It is true that sometimes you can't 
see the answer when it is staring you in the face.

Thanks again,

Katt



More information about the Tutor mailing list