Python写CSV文件时多出空行

1 投票
2 回答
2572 浏览
提问于 2025-04-18 03:56

我有一段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()

2 个回答

0

我发现使用'b'这个选项可以解决我的问题,具体可以查看API文档:https://docs.python.org/2/library/functions.html?highlight=open#open

3

这个问题在评论中已经解答了。问题出在使用了 wb 模式,而不是 ab 模式。

撰写回答