【发布时间】:2014-06-08 11:23:06
【问题描述】:
我有一段 python 代码应该打开(或创建)一个 CSV 文件并在其末尾附加一个新行。但是,在每个条目之间添加了一个额外的空白行。有没有办法避免这种情况?
我有大约 500 个脚本实例,它们都访问同一个文件,尽管(理论上)它们应该在不同的时间访问该文件。
def writeBest(fileName, savePath, data):
# Create a filename
name = "BEST_" + fileName + ".csv"
# Create the complete filename including the absolute path
completePath = os.path.join(savePath, fileName)
# Check if directory exists
if not os.path.exists(completePath):
os.makedirs(completePath)
completeName = os.path.join(completePath, name)
# Write the data to a file
theFile = open(completeName, 'wb')
writer = csv.writer(theFile, quoting=csv.QUOTE_ALL)
writer.writerow(data)
# Close the file
theFile.close()
【问题讨论】:
-
什么是数据?哪种类型?
-
如果你想添加到 csv 文件,我想你想用
ab模式打开它,而不是wb。 -
文件不存在需要创建
-
@ChrisHeadleand 如果文件不存在,
'a'模式将创建文件。 (自己测试一下。)无论如何,你能告诉我们你的data参数吗? -
@ChrisHeadleand w 将覆盖一个已经存在的文件而不是添加到它。