简体   繁体   English

为什么多次运行 python 脚本时 CSV 文件中会添加空行?

[英]Why are blank lines being added in CSV file when running python script multiple times?

I am currently trying to build a python 3 script that will take a csv file, read it, and then copy the rows and add them to the end of a file.我目前正在尝试构建一个 python 3 脚本,该脚本将获取一个 csv 文件,读取它,然后复制行并将它们添加到文件的末尾。 This script is going to run daily as the data dump from the application will run daily.此脚本将每天运行,因为来自应用程序的数据转储将每天运行。

I have the code "working" to get the file and copy it and it does work on each run, but it is adding several blank lines to the end of the file each time.我有代码“工作”来获取文件并复制它,它在每次运行时都可以工作,但每次都会在文件末尾添加几个空行。 so for instance the first time i run it, it is on lines 1-101, but the next time it might be lines 9000-9101.所以例如我第一次运行它时,它在第 1-101 行,但下一次它可能是第 9000-9101 行。

newest = r'C:\Users\me\downloads\Test2.csv'
with open(r'C:\Users\me\downloads\out.csv', 'a', newline='') as repository:
    fileWriter = csv.writer(repository, delimiter=',')
    with open(newest, 'r', newline='') as newData:
        fileReader = csv.reader(newData, delimiter=',')
        next(fileReader)
        for row in fileReader:
            fileWriter.writerow(row)


print("Copy Complete")

I would like for it to not have the blank lines between it.我希望它之间没有空行。 as it may cause issues with the app I am trying to use to view the data.因为它可能会导致我试图用来查看数据的应用出现问题。

Sounds like the csv that you're using as the input contains blank lines.听起来像您用作输入的 csv 包含空行。 I'd add a check in your for row loop to make sure that you're only adding lines with data in them to your output file.我会在您的 for row 循环中添加一个检查,以确保您只将带有数据的行添加到您的 output 文件中。 This thread may be helpful to checking on if the lines in your input file are blank or not. 该线程可能有助于检查输入文件中的行是否为空白。

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

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