Python:逐行从文件中添加整数

时间:2018-04-03 21:24:55

标签: python python-3.x

我希望我的程序计算出某些数字的平均值,这些数字存储在.txt文件Integers.txt中。共有98个数字,每个数字占1行。我怎样才能弄清楚它的意思,称之为“平均长度”#34; 下面代码中的所有内容都有效,我只是在努力找到一种方法将它们加在一起,然后将它们除以有多少(平均值)。

这是我的代码:

def AddSongLengths():
    conn = sqlite3.connect("xxxxx.db")
    c=conn.cursor()
    PlaylistInput = input("Select which Playlist you want to calculate the mean of: ")
    Length = c.execute('SELECT "Length" FROM {0}'.format(PlaylistInput))
    file=open("Integers.txt", "w")
    for row in c.fetchall():
        TrackSeconds = TrackIntoSeconds("{0}".format(row[0]))
        file.writelines("""
        {0}""".format(TrackSeconds))
    file.close()

1 个答案:

答案 0 :(得分:0)

所以你想计算整数列表的平均值然后将它们附加到文件中?

def AddSongLengths():
    conn = sqlite3.connect("xxxxx.db")
    c=conn.cursor()
    PlaylistInput = input("Select which Playlist you want to calculate the mean of: ")
    Length = c.execute('SELECT "Length" FROM {0}'.format(PlaylistInput))
    file=open("Integers.txt", "w")
    sum = 0
    count = 0
    for row in c.fetchall():
        TrackSeconds = TrackIntoSeconds("{0}".format(row[0]))
        file.writelines("""
        {0}""".format(TrackSeconds))
        try:
            sum += int(row[0])
            count += 1
    avg = sum / count
    file.writelines("{}".format(avg))
    file.close()

这应该可行 - 可能需要一点调试:)