我是一个完整的新手,我有以下脚本.. 它将一些随机数据写入.csv。我的最终目标是保留这个预先存在的.csv,但是在一个单独的Python脚本中将一个随机生成的数据点添加到此csv的开头。
完全是新的 - 不知道如何去做这件事。谢谢你的帮助。
output = [a,b]
d = csv.writer(csvfile, delimiter=',', quotechar='|',
quoting=csv.QUOTE_MINIMAL)
d.writerow(output)
答案 0 :(得分:1)
您确定要将其添加到文件的开头吗?我觉得你想把它添加到最后,或者如果你想在开头添加它,你至少想把它放在标题行之后,即['name','value']。
当我尝试自己编译时,你当前的脚本有几个错误,所以我可以帮你解决一下。
r'C:/Users/AMB/Documents/Aptana Studio 3 Workspace/RAVE/RAVE/resources/csv/temperature.csv'
output = [timeperiod, temp,]
转到插入单个数据点的脚本。此脚本读入您现有的文件。在标题下面的第二行插入一个新行(您将使用随机值,我使用1表示时间,2表示值)。如果这不是您正在寻找的,请告诉我。
directory = r"C:/Users/AMB/Documents/Aptana Studio 3 Workspace/RAVE/RAVE/resources/csv/temperature.csv"
with open(directory, 'r') as csvfile:
s = csvfile.readlines()
time = 1
value = 2
s.insert(2, '%(time)d,%(value)d\n\n' % \
{'time': time, "value": value})
with open(directory, 'w') as csvfile:
csvfile.writelines(s)
下一节是对评论中更详细的问题的回应:
import csv
import random
directory = r"C:\Users\snorwood\Desktop\temperature.csv"
# Open the file
with open(directory, 'r') as csvfile:
s = csvfile.readlines()
# This array will store your data
data = []
# This for loop converts the data read from the text file into integers values in your data set
for i, point in enumerate(s[1:]):
seperatedPoint = point.strip("\n").split(",")
if len(seperatedPoint) == 2:
data.append([int(dataPoint) for dataPoint in seperatedPoint])
# Loop through your animation numberOfLoops times
numberOfLoops = 100
for i in range(numberOfLoops):
if len(data) == 0:
break
del data[0] # Deletes the first data point
newTime = data[len(data) - 1][0] + 1 # An int that is one higher than the current last time value
newRandomValue = 2
data.append([newTime, newRandomValue]) # Adds the new data point to the end of the array
# Insert your drawing code here
# Write the data back into the text file
with open(directory, 'w') as csvfile: #opens the file for writing
temperature = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) # The object that knows how to write to files
temperature.writerow(["name", "values"]) # Write the header row
for point in data: # Loop through the points stored in data
temperature.writerow(point) # Write current point in set