簡體   English   中英

從 Arduino 將新數據寫入 Python 中的 csv 文件

[英]Write new data in to csv file in Python from an Arduino

我每秒都從 Arduino 接收數據,但我無法保存它,它將連續數據寫入 csv 文件的同一單元格中,並且每次獲取新值時都會對其進行更改。 我正在嘗試使用 newline='' 和寫入行,但沒有工作。

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)

問題可以使模式w+ (打開文件時刪除所有數據)和with f:關閉文件。

我看到兩種可能的解決方案:

第一:只打開一次文件 - 在開始時 - 只在最后關閉一次。

# 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()

但是當程序出錯時可能會丟失數據。

第二種:使用模式a追加數據

# ... 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 ...

您可以在寫入后直接使用with關閉文件。


編輯:

如果您只想寫一行有兩個值,那么您應該使用名稱中不帶 char s writerow

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`

如果你有很多行,那么你可以使用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`

順便提一句:

即使對於行中的單個值,您也必須使用列表

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

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

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

這是這樣的:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM