打开一个CSV文件一次,然后从循环python向它写入几行代码

2024-09-24 22:26:42 发布

您现在位置: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)

我试图找到一种方法来生成文件,保持它打开,调用上面的方法,并将所有文本写入其中,而不使文件重写自身。你知道吗


Tags: 文件csvcsvfile方法namedefaswith
2条回答

使用: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文件,您可以使用一个具有实例状态的类和一个方法来进行写入,这样每个文件可以单独清除一次并附加多次。在这种情况下,由于对打开的文件句柄数量的限制,每次使用append时重新打开要比打开一次并保持打开更慢但更安全。您可以使用缓存,以便该类也是任何给定文件名的单例:

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

它简单地获取一个实例(如果需要的话创建一个实例),然后写一次,或者它可以创建和存储一个实例并重用它(节省了缓存查找的开销,但在功能上是相同的)。你知道吗

相关问题 更多 >