将变量导出到Excel电子表格

时间:2017-10-01 18:42:25

标签: python excel

我制作了一个计算绿蝇种群的程序。我正在努力的一项任务是将一系列变量导出到excel。我已经为绿蝇计算了数学,但我无法弄清楚如何将它放入电子表格中。这是代码:

import winsound
import time
winsound.PlaySound("SystemHand", winsound.SND_ALIAS)  #startup
#menu
print("Greenfly population model")
time.sleep(1)
one=1
print("1: Set the generation 0 values")
time.sleep(1)
two=2
print("2: Display the generation 0 values")
time.sleep(1)
three=3
print("3: Run the model")
time.sleep(1)
four=4
print("4: Export the data")
time.sleep(1)
five=5
print("5: Quit")
time.sleep(1)
#base code
while True: #wont shut down till option 5 is entered
    print("")
    ans=int(input("Please enter the number of the choice you want "))

    if ans == one:
        while True:
            generations=float(input("Enter the number of generations you want the model to run for (Must be in 5 and 25 inclusive) "))
            if generations < 5 or generations > 25:
                print("Between 5 and 25 please")
            else:
                break
        while True:
                adultsur = float(input("Choose adult survival rate between 0 and 1 "))
                if adultsur < 0 or adultsur > 1:
                    print ("Between 1 and 0 please")  #wont mess up the decimals
                else:
                    break
        while True:
            juvensur=float(input("Choose juvenile survivle rate between 0 and 1 "))
            if juvensur < 0 or juvensur > 1:
                print ("Between 1 and 0 please")
            else:
                break
        while True:
            sensur=float(input("Choose senile survivle rate between 0 and 1 "))
            if sensur < 0 or sensur > 1:
                print ("Between 1 and 0 please")
            else:
                break
        juv=int(input("Choose the amount of juveniles "))
        adu=int(input("Choose the amount of adults "))  #had issue with floats here so left it as int(input())
        sen=int(input("Choose the amount of seniles "))
        birth=int(input("Enter the birthrate of the adults "))

    if ans == two:
        print("The new generation to model is ",generations)    #no issues here
        time.sleep(1)
        print("The adult survivul rate is ",adultsur)
        time.sleep(1)
        print("The juvenile survivul rate is ",juvensur)
        time.sleep(1)
        print("The senile survivul rate is ",sensur)
        time.sleep(1)
        print("There are ",juv," juveniles")
        time.sleep(1)
        print("There are ",adu," juveniles")
        time.sleep(1)
        print("There are ",sen," juveniles")
        time.sleep(1)
        print("The birthrate of adults is ",birth)

    if ans == three:
        print("Running module.")
        time.sleep(0.1)
        print("Running module..")
        time.sleep(0.1)
        print("Running module...")
        time.sleep(0.1)
        counter = 0
        print("GENERATION    JUVENILES    ADULTS    SENILES")
        while generations > counter:
            print ("",int(counter),"   ", int(juv),"    ", int(adu),"   ", int(sen))
            int(sen)
            int(adu)#gets rid off the neverending decimals and rounds it up
            int(juv)
            sen *= sensur       #takes out the old seniles
            adu *= adultsur     #does the math in a much simpler way than basic maths
            juv *= len
            juvn = juv
            juv = adu * birth
            sen += adu
            adu += juvn
            counter= counter+1    #will only repeat how many times the code was set to run

    if ans == four
            print ("",int(counter),"   ", int(juv),"    ", int(adu),"   ", int(sen))
            int(sen)
            int(adu)
            int(juv)
            sen *= sensur
            adu *= adultsur 
            juv *= len
            juvn = juv
            juv = adu * birth
            sen += adu
            adu += juvn
            counter= counter+1

    if ans == five:
        print("Understandable, have a great day")
        winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
        winsound.PlaySound("*", winsound.SND_ALIAS)
        break

我可以帮助您导出它或者只教我如何操作。 感谢。

1 个答案:

答案 0 :(得分:0)

您可以通过多种方式在Excel中编写数据,另外还有多种格式可供使用。

Python csv模块实现了可用于编写和读取表格数据的类。要写入文件,您可以使用csv.writer,也可以使用csv.DictWriter

csv.writer返回一个writer对象,负责将数据转换为分隔字符串。以下是如何使用它的示例:

import csv

data_header = ['id', 'width', 'height']
data = [[0, 10, 5],
        [1, 2, 3],
        [2, 50, 40]]

with open('test.csv', 'w') as file_writer:
    writer = csv.writer(file_writer)

    writer.writerow(data_header)
    for item in data:
        writer.writerow(item)

csv.DictWriter返回一个像常规编写器一样操作但将字典映射到输出行的对象。以下是如何使用它的示例:

import csv

data_header = ['id', 'width', 'height']
data = [{'id': 0, 'width': 10, 'height': 5},
        {'id': 1, 'width': 2, 'height': 3},
        {'id': 2, 'width': 50, 'height': 40}]

with open('test.csv', 'w') as file_writer:
    dict_writer = csv.DictWriter(file_writer, data_header)

    dict_writer.writeheader()
    for item in data:
        dict_writer.writerow(item)

如您所见,csv.writercsv.DictWriter之间的区别在于您如何向界面提供数据。在csv.writer中,您在列表中提供数据,并且您负责保持列表中的顺序,以便将其写入正确的列中,并在csv.DictWriter中提供字典,其中键是列名称和值是列的数据。