简体   繁体   中英

How to add a data point to an already existing .csv (with Python)?

I am a complete newb at this and I have the following script.. It writes some random data to .csv. My end goal is to keep this preexisting .csv but add ONE random generated datapoint to the beginning of this csv in a separate Python script.

Completely new at this -- not sure how to go about doing this. Thanks for your help.

    output = [a,b]

    d = csv.writer(csvfile, delimiter=',', quotechar='|', 

    quoting=csv.QUOTE_MINIMAL)  
    d.writerow(output)

Are you sure you are trying to add it to the start of the file? I feel like you would want to add it to the end or if you did want to add it at the beginning you would at least want to put it after the header row which is ['name', 'value'].

As it stands your current script has several errors when I try to compile it myself so I can help you out a bit there.

  1. The directory string doesn't work because of the slashes. It will work if you add an r in front (for raw string) like so r'C:/Users/AMB/Documents/Aptana Studio 3 Workspace/RAVE/RAVE/resources/csv/temperature.csv'
  2. You don't need JSON to import json or logging if this is the entirety of your code.
  3. Inside of your for loop you redefine the temperature writer which is unnecessary, your definition at the start is good enough.
  4. You have an extra comma in your the line output = [timeperiod, temp,]

Moving on to a script that inserts a single data point. This script reads in your existing file. Inserts a new line (you would use random values, I used 1 for time and 2 for value) on the second line which is beneath the header. Let me know if this isn't what you are looking for.

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)

This next section is in response to your more detailed question in the comments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM