簡體   English   中英

一次打開CSV文件,然后從循環python向其中寫入幾行

[英]open a CSV file once and write several lines to it from a loop python

方法如下:

def generateCSVfile(fileName,fileDescription,fileLocation,md5Hash):
    with open('deploymentTemplate.csv', 'w') as csvfile:
        createRow = csv.writer(csvfile,
                                 quoting=csv.QUOTE_MINIMAL)

這會生成我的CSV文件,但是由於我是在循環中調用它,因此它會覆蓋自身。

generateCSVfile(name, fileDescription, filePath+"/"+name, md5Hash)

我試圖找到一種方法來生成文件,使其保持打開狀態,調用上述方法,並在不覆蓋文件自身的情況下將所有文本寫入文件。

使用: open('deploymentTemplate.csv', 'a')附加值。

語法: open(<file_name> [,<mode>])

不同的模式是:

  • 僅讀取文件時,模式可以為'r'
  • 'w'僅用於寫入(具有相同名稱的現有文件將被刪除)
  • 'a'打開文件進行追加,寫入文件的所有數據都會自動添加到末尾。
  • 'r+'打開文件以供讀取和寫入。

    mode參數是可選的; 如果省略,則假定為“ r”。

例如:

with open("test.txt", "a") as myfile:
    myfile.write("appended text")

如果文件需要在每次程序運行時清空一次,但是在一次運行中要追加多次,則始終可以使用全局(或類成員狀態)來確保只打開一次。

import atexit

csvfile = None
def generateCSVfile(fileName,fileDescription,fileLocation,md5Hash):
    global csvfile
    if csvfile is None:
        # Lazily open file on first call
        csvfile = open('deploymentTemplate.csv', 'w')
        atexit.atexit(csvfile.close)  # Close cleanly on program exit

    try:
        csvwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL, newline='')
        # do whatever writing you need to csvwriter
    finally:
        csvfile.flush()  # Match behavior of repeated with/open, force predictable flush

如果可能涉及多個CSV文件,則可以使用具有實例狀態的類和一種方法來進行寫入,因此每個文件可以獨立清除一次並附加多次。 在這種情況下,由於打開文件句柄的數量受到限制,因此每次使用后重新打開以進行附加操作比打開一次並保持打開狀態更慢但更安全。 您可以使用緩存,因此該類對於任何給定的文件名也是單例的:

import weakref

class CSVGenerator:
    CACHE = {}
    CACHELOCK = threading.Lock()

    def __new__(cls, csvfilename):
        canonicalname = os.path.realpath(csvfilename)
        newself = super().__new__(cls)
        with cls.CACHELOCK:
            self = cls.CACHE.setdefault(canonicalname, newself)
            if newself is self:
                # First time we opened this file, clear file and initialize instance
                with open(canonicalname, 'w') as f:
                    pass
                self.csvfilename = canonicalname
                self.appendlock = threading.Lock()
        return self

    def generateCSVfile(self, fileName, fileDescription, fileLocation, md5Hash):
        with newself.appendlock, open(self.csvfilename, 'a', newline='') as csvfile:
            createRow = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
            # Perform writes to file

該類的用法可以是:

 CSVGenerator(somecsvfilename).generateCSVfile(...args...)

它會短暫獲取一個實例(如果需要,可以創建一個實例),然后編寫一次,或者它可以創建並存儲實例並重用它(節省了緩存查找的開銷,但功能相同)。

暫無
暫無

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

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