user16239103
user16239103

Reputation:

Write new data in to csv file in Python from an Arduino

I'm receiving data from an Arduino each second but I can't save it, it writes the continous data in the same cell on the csv file and just is changed it each time that the new value is getted. I'm triying with the newline='' and the write row but is not working.

valueenc = (value)
                print("Valueencoded", valueenc)
                #print("Message received: "  + valueenc)
                f = open(f'{root_path}/Desktop/microphone_dump.csv','w+', newline ='')
                #f.write(valueenc)
                with f:
                    write = csv.writer(f) 
                    write.writerows(valueenc)

Upvotes: 0

Views: 416

Answers (2)

furas
furas

Reputation: 142919

Problem can make mode w+ (which deletes all data when you open file) and with f: which closes file.

I see two possible solutions:

First: open file only once - at start - and close it only once - at the end.

# at start
f = open(f'{root_path}/Desktop/microphone_dump.csv', 'w+')

# ... code ...

valueenc = value
print("Valueencoded", valueenc)
write = csv.writer(f) 
write.writerows(valueenc)

# ... code ...

# at the end
f.close()

But it may lost data when program get error.

Second: use mode a to append data

# ... code ...

valueenc = value
print("Valueencoded", valueenc)

with open(f'{root_path}/Desktop/microphone_dump.csv', 'a') as f:
    write = csv.writer(f) 
    write.writerows(valueenc)

# ... code ...

And you can use with to close file directly after writing.


EDIT:

If you want to write only one row with two values then you should use writerow without char s in name.

with open(f'{root_path}/Desktop/microphone_dump.csv', 'a') as f:
    write = csv.writer(f) 
    write.writerow( [value1, value2] )  # without `s` in name `writerow`

And if you would have many rows then you could use writerows

rows = [
   [value1, value2],   # row 1
   [value3, value4],   # row 2
]

with open(f'{root_path}/Desktop/microphone_dump.csv', 'a') as f:
    write = csv.writer(f) 
    write.writerows( rows )  # with `s` in name `writerows`

BTW:

Even for single value in row you have to use list(s)

    write.writerow( [value1] )  # without `s` in name 

and

rows = [
   [value1],   # row 1
   [value2],   # row 2
]

    write.writerows( rows )  # with `s` in name `writerows`

Upvotes: 0

user16239103
user16239103

Reputation:

this is the way:

file = open(f'{root_path}/Desktop/test.csv', "a")
                print("Created file")
                file = open(f'{root_path}/Desktop/test.csv', "a") #append the data to the file
                file.write(valueenc + "\n") #write data with a newline
                #close out the file
                file.close()

Upvotes: 0

Related Questions