簡體   English   中英

如何使用 Python 在 CSV 中寫入新行

[英]How to write new rows in a CSV using Python

我有這個生成隨機數的代碼。 我希望它每次運行時將隨機數保存在新的行/行上(代碼)。

我嘗試添加newLinenewRow但它沒有用。

import csv
import random

newFile = open("random.csv",'w',newline='')
newWriter = csv.writer(newFile, dialect='excel')
newRow = []
case_number = random.randint(0,1000000000)
print("Your problem has been stored. We have allocated a case number which  will be sent off to a technician. Please take a note of your case number: ",  str(case_number))
newRow.append(case_number)
newWriter.writerow(newRow)
newFile.close()

我怎樣才能縮短這段代碼?

任何幫助將不勝感激。

謝謝!

我對原始代碼做了一些小的修改。

按照@JRodDynamite 的建議,將“w”替換為“a”(附加) - 以便將先前的數據保存在文件中,並附加新數據

添加了“with” - 正如@Display Name 所建議的 - 確保在使用它的代碼完成運行時“清理”資源。

將 case_number 定義為字符串(隨機整數的轉換)。

我繼續使用@Jason Cole 使用的 CSV 編寫器。

我刪除了 newRow 和追加。

import csv
import random

with open("random.csv",'a') as newFile:
    newWriter = csv.writer(newFile, dialect='excel')
    case_number = str(random.randint(0,1000000000))
    print("Your problem has been stored. We have allocated a case number which  will be sent off to a technician. Please take a note of your case number: ",  case_number)
    newWriter.writerow([case_number])
    newFile.close()

暫無
暫無

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

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