python: write input to file and save it

So, I started doing some python recently and I have always like to lift some weights as well. Therefore, I was thinking about a little program where I can put in my training progress (as some kind of python excercise). I do something like the following as an example:

from sys import argv

file = argv[1]
target_file = open(file, 'w')
weigth = raw_input("Enter what you lifted today: ")
weigth_list = []
weigth_list.append(weigth)
file.write(weigth_list)
file.close()

Now, I know that a lot is wrong here but this is just to get across the idea I had in mind. So what I was hoping to do, was creating a file and getting a list into and store the "raw_input()" in that file. Then I want to save that file and the next time I run the script (say after the next training), I want to save another number and put that to the list. Additionally, I want to do some plotting with the data stored in the list and the file. Now, I know I could simply do that in Excel but I would prefer to do it in python. Hopefully, someone understood what I mean.


Unsure what exactly your weight_list looks like, or whether you're planning this for one specific workout or the general case, but you'll probably want to use something like a CSV (comma-separated values) format to save the info and be able to easily plot it (for the general case of N different workout types). See below for what I mean:

$ ./record-workout saved-workouts.csv

where the record-form is

<workout type>,<number of sets>,<number of reps>,<weight>

and saved-workouts.csv is the file we'll save to

then, modifying your script ever-so-slightly:

# even though this is a small example, it's usually preferred
# to import the modules from a readability standpoint [1]
import sys

# we'll import time so we can get todays date, so you can record
# when you worked out
import time

# you'll likely want to check that the user provided arguments
if len(sys.argv) != 2:
    # we'll print a nice message that will show the user
    # how to use the script
    print "usage: {} <workout_file>".format(sys.argv[0])

    # after printing the message, we'll exit with an error-code
    # because we can't do anything else!
    sys.exit(1)

# `sys.argv[1]` should contain the first command line argument,
# which in this case is the name of the data file we want
# to write to (and subsequently read from when we're plotting)
# therefore, the type of `f` below is `str` (string).
#
# Note: I changed the name from `file` to `filename` because although `file`
# is not a reserved word, it's the name of a built-in type (and constructor) [2]
filename = sys.argv[1]

# in Python, it's recommended to use a `with` statement 
# to safely open a file. [3] 
#
# Also, note that we're using 'a' as the mode with which 
# to open the file, which means `append` rather than `write`.
# `write` will overwrite the file when we call `f.write()`, but
# in this case we want to `append`.
# 
# Lastly, note that `target_file` is the name of the file object,
# which is the object to which you'll be able to read or write or append.
with open(filename, 'a') as target_file:

    # you'd probably want the csv-form to look like
    #   
    #   benchpress,2,5,225
    #
    # so for the general case, let's build this up
    workout = raw_input("Enter what workout you did today: ")
    num_sets = raw_input("Enter the number of sets you did today")
    num_reps = raw_input("Enter the number of reps per set you did today")
    weight = raw_input("Enter the weight you lifted today")

    # you might also want to record the day and time you worked out [4]
    todays_date = time.strftime("%Y-%m-%d %H:%M:%S")

    # this says "join each element in the passed-in tuple/list 
    # as a string separated by a comma"
    workout_entry = ','.join((workout, num_sets, num_reps, weight, todays_date))

    # you don't need to save all the entries to a list, 
    # you can simply write the workout out to the file obj `target_file`
    target_file.write(workout_entry)

    # Note: I removed the `target_file.close()` because the file closes when the 
    # program reaches the end of the `with` statement.

The structure of saved-workouts.csv would thus be:

workout,sets,reps,weight
benchpress,2,5,225

This would also allow you to easily parse the data when you're getting ready to plot it. In this case, you'd want another script (or another function in the above script) to read the file using something like below:

import sys

# since we're reading the csv file, we'll want to use the `csv` module
# to help us parse it
import csv

if len(sys.argv) < 2:
    print "usage: {} <workout_file>".format(sys.argv[0])
    sys.exit(1)

filename = sys.argv[1]

# now that we're reading the file, we'll use `r`
with open(filename, 'r') as data_file:
    # to use `csv`, you need to create a csv-reader object by
    # passing in the `data_file` `file` object
    reader = csv.reader(data_file)

    # now reader contains a parsed iterable version of the file
    for row in reader:
        # here's where you'll want to investigate different plotting
        # libraries and such, where you'll be accessing the various
        # points in each line as follows:
        workout_name = row[0]
        num_sets = row[1]
        num_reps = row[2]
        weight = row[3]
        workout_time = row[4]
        # optionally, if your csv file contains headers (as in the example
        # above), you can access fields in each row using:
        #
        # row['weight'] or row['workout'], etc.

Sources:

[1] https://softwareengineering.stackexchange.com/questions/187403/import-module-vs-from-module-import-function

[2] https://docs.python.org/2/library/functions.html#file

[3] http://effbot.org/zone/python-with-statement.htm

[4] How to get current time in Python

链接地址: http://www.djcxy.com/p/40928.html

上一篇: 简单从Python中的类继承将引发错误

下一篇: python:将输入写入文件并保存