简体   繁体   中英

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?

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

The following should work fine in 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. If you do not use the ab mode, it will result in an extra empty row per call of writerow .

If you are using Python 3.x, you would need the following:

# Creating output dictwriter for results

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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