简体   繁体   English

Python-有时会将CSV文件的附加行添加到前一行的末尾

[英]Python - Sometimes an appended row to a CSV file is added to the end of the previous row

Opening an exiting file and writing a dictionary to it sometimes appends the dictionary (being written as a row) to the end of the previous line. 打开一个退出的文件并向其中写入字典有时会将字典(被写为一行)附加到前一行的末尾。 How would I setup this code to always prevent that? 我将如何设置此代码以始终防止这种情况? It seems to only happen when a previous code 'run' has crashed and I have restarted the code and it begins to write to a file from a previous run (which I want - just not added onto the end of a previous line). 似乎只有在先前的代码“运行”崩溃并且我已经重新启动代码并且它开始从先前的运行写入文件时才发生(我想要的-只是不添加到前一行的末尾)。

        #Creating output dictwriter for results
        with open(csv, 'a', 0) as outputFile:
            fieldnames = csvCols
            successWriter = csv.DictWriter(outputFile, fieldnames=fieldnames)
            successWriter.writerow(out_dict)
        outputFile.close()

Would opening the file in 'ab' mode make a difference? 以“ ab”模式打开文件会有所不同吗?

您通常会在文件行中添加“ \\ n”,以便将其写入下一行。

The following should work fine in Python 2.x: 以下内容在Python 2.x中应该可以正常工作:

# Creating output dictwriter for results

with open(csv, 'ab') as outputFile:
    successWriter = csv.DictWriter(outputFile, fieldnames=csvCols)
    successWriter.writerow(out_dict)

The with statement will automatically close your file, even if there is a problem with your script. 即使您的脚本有问题, with语句也会自动关闭文件。 If you do not use the ab mode, it will result in an extra empty row per call of writerow . 如果不使用ab模式,则每次调用writerow都会导致多余的空行。

If you are using Python 3.x, you would need the following: 如果您使用的是Python 3.x,则需要满足以下条件:

# Creating output dictwriter for results

with open(csv, 'a', newline='') as outputFile:
    successWriter = csv.DictWriter(outputFile, fieldnames=csvCols)
    successWriter.writerow(out_dict)

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

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