以下方法:
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”。
例如:
如果每次程序运行都需要清空一次文件,但在一次运行中需要多次追加,则可以始终使用全局(或类成员状态)来确保只打开一次。你知道吗
如果可能涉及多个CSV文件,您可以使用一个具有实例状态的类和一个方法来进行写入,这样每个文件可以单独清除一次并附加多次。在这种情况下,由于对打开的文件句柄数量的限制,每次使用append时重新打开要比打开一次并保持打开更慢但更安全。您可以使用缓存,以便该类也是任何给定文件名的单例:
类的用法可以是:
它简单地获取一个实例(如果需要的话创建一个实例),然后写一次,或者它可以创建和存储一个实例并重用它(节省了缓存查找的开销,但在功能上是相同的)。你知道吗
相关问题 更多 >
编程相关推荐