简体   繁体   English

Python,编写CSV文件时有多余的空白行

[英]Python, writing CSV file has extra blank rows

I have a piece of python code which is supposed to open (or create) a CSV file and append a new row to the end of it. 我有一段python代码,应该打开(或创建)CSV文件并将新行添加到它的末尾。 However, there is an extra blank line added between each entry. 但是,在每个条目之间添加了一个额外的空白行。 Is there a way to avoid this? 有办法避免这种情况吗?

I have around 500 instances of the script which all access the same file, though (in theory) they should access the file at different times. 我有大约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()

Problem answered through comments. 问题通过评论回答。 The issue was using the wb mode not ab mode. 问题是使用wb模式而不是ab模式。

“ b”选项对我有用,请查看API文档: https : //docs.python.org/2/library/functions.html? highlight = open# open

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM