创建excel文件,并使用Python将所有电压结果保存到其中



我想制作一个Python代码,用一系列给定的电流和固定的电阻值来计算电压。V=IR……R为5欧姆。当前列表[1,2,3,4,5,6,7,8,9,10]。Python将创建一个Excel文件,所有电压结果将被添加并保存在Excel中。

OP想要一个简单的代码,所以我会这么做。注意,您可能需要更改代码以满足您的需求。

current = [1,2,3,4,5,6,7,8,9,10] # Current list
r = 5 # R = 5 ohm
voltage = [] # A "place holder" list for holding the voltage values
# A for loop to loop through each value in the list
for i in current:
voltage.append(i*r) # Calculate the voltage by V = I*R, then append that value to the place holder list
# Open a file and write to it
# In this example we will write to the CSV format
# In CSV, each value is separated by a comma (",")
f = open("output.csv", "w")
f.write("Current,Voltagen") # Header of two columns
# Write each pair of current and voltage to the file
for i in range(0, len(current)):
f.write(str(current[i]) + "," + str(voltage[i]) + "n")
f.close() # Close the file

或者更简单的版本:

current = [1,2,3,4,5,6,7,8,9,10] # Current list
r = 5 # R = 5 ohm
# Open a file and write to it
# In this example we will write to the CSV format
# In CSV, each value is separated by a comma (",")
f = open("output.csv", "w")
f.write("Current,Voltagen") # Header of two columns
# A for loop to loop through each value in the list
for i in current:
f.write(str(i) + "," + str(i*r) + "n") # Calculate the voltage by V = I*R, then write to file
f.close() # Close the file

之后,您可以在Excel中打开文件并查看结果。

如果需要xlsx文件,请使用Excel格式库。

最新更新