python:将输入写入文件并保存

时间:2015-11-19 01:18:30

标签: python

所以,我最近开始做一些python,我也总是想提升一些重量。因此,我正在考虑一个小程序,我可以在其中加入我的训练进度(作为某种python练习)。 我做了类似以下的事情作为例子:

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()

现在,我知道这里有很多错误,但这只是为了理解我的想法。所以我希望做的是创建一个文件并获取一个列表并将“raw_input()”存储在该文件中。然后我想保存该文件,下次运行脚本时(比如下一次训练后),我想保存另一个号码并将其放入列表中。另外,我想用列表和文件中存储的数据进行一些绘图。 现在,我知道我可以在Excel中执行此操作,但我更愿意在python中执行此操作。希望有人理解我的意思。

1 个答案:

答案 0 :(得分:3)

不确定您的weight_list到底是什么样的,或者您是为一个特定的锻炼或一般情况计划这个,但您可能希望使用类似CSV(逗号分隔值)格式的内容保存信息并能够轻松地绘制它(对于N种不同锻炼类型的一般情况)。请参阅下文,了解我的意思:

$ ./record-workout saved-workouts.csv

记录表单是

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

saved-workouts.csv是我们要保存到的文件

然后,稍微修改你的脚本:

# 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.

saved-workouts.csv的结构因此是:

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

这也可以让您在准备绘制数据时轻松解析数据。在这种情况下,您需要另一个脚本(或上述脚本中的其他函数)使用以下内容读取文件:

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.

来源:

[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