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中做到这一点。 希望有人明白我的意思。


不确定你的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]如何在Python中获取当前时间

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

上一篇: python: write input to file and save it

下一篇: Python. How to create a local datetime with datetime.today()