开发者

Export data elements to text file in Python

How could I alter the following code to get a table of data elements in a text file to be plotted in excel?

 x = z = vz = vy = ax = ay = time = 0.0
 y = 50 #Initial Height: 50 meters
 vx = 25 #Initial velocity in the x direction: 25 m/s
 az = -9.8 #Constant acceleration in the z direction: -9.8 m/s^2
 deltaTime = 1

 #Initializes a matrix with 3 columns and 1000 rows for each column: Will hold the corresponding x,y,z coordinate of the particle at time t
 positionMatrix = [[None]*1000 for x in range(3)] 

 posArray = [x, y, z] 
 velArray = [vx, vy, vz] 
 accArray = [ax, ay, az]
 timeArray = [i*deltaTime for i in range(1000)]
 #print(timeArray)

 for j in range (1000): #j is the time increment
     for i in range (3): #i is each component (x,开发者_如何学编程 y, z)

         #x = x + vx*time + .5*ax*(time*time); #y = y + vy*time + .5*ay*(time*time); #z = z + vz*time + .5*az*(time*time)
         positionMatrix[i][j] = posArray[i] + velArray[i] * timeArray[j] + 1/2*accArray[i] * timeArray[j] * timeArray[j]
         print(positionMatrix)


Probably the best way to save a file for opening in Excel is to use the builtin CSV module. It will allow you to save a file that can be imported in Excel and other spreadsheet apps.

Create a CSV writer and use the writerows method, passing your positionMatrix list.

Please take a look at python docs: 13.1. csv — CSV File Reading and Writing


A very simple way to import data into Excel is to write it as a CSV (comma separated value) file. Each line represents a row, and you split the cells with commas. For example:

1,2,4
2,5,6,7
abc,1,hello

Save this as a .csv file, and Excel will open it. If you want to do more calculations in Excel, you can use Excel to save it as a .xls file.

If you want to save directly to an Excel file from Python, you could try the modules at http://www.python-excel.org/. But it's almost certainly easier to use CSV!


Not sure exactly what you mean but I'm guessing you want a CSV file to open in Excel. In that case use open() to create a file for writing in, write() values and commas into that file while looping, and then close() the file at the end of your program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜