简体   繁体   English

在 python 中使用 writer 后行之间的空白

[英]Empty space in between rows after using writer in python

I am using csv package now, and every time when I write to a new csv file and open it with excel I will find a empty row in between every two rows.我现在正在使用 csv 包,每次写入新的 csv 文件并用 excel 打开它时,我都会在每两行之间找到一个空行。

filereader = csv.reader(open("tests.csv", "r"), delimiter=",")
filewriter = csv.writer(open("test_step1.csv", "w"), delimiter=",")
#Delete header
for row in filereader:
    if row[0].isdigit():
        filewriter.writerow(row)

You need to open the file in wb mode try: 你需要在wb模式下打开文件试试:

import csv

filereader = csv.reader(open("tests.csv", "r"), delimiter=",")
filewriter = csv.writer(open("test_step1.csv", "wb"), delimiter=",", newline="")
#Delete header
for row in filereader:
    if row[0].isdigit():
        filewriter.writerow(row)

The csv.writer writes \\r\\n into the file directly. csv.writer直接将\\ r \\ n写入文件。

If you don't open the file in binary mode , it will write \\r\\r\\n because on Windows text mode will translate each \\n into \\r\\n . 如果不以二进制模式打开文件,它将写入\\ r \\ n \\ n \\ n \\ n \\ n因为在Windows文本模式下会将每个\\ n转换为\\ r \\ n

edit: 编辑:

For python 3 had to add newline="" to csv.writer as per this answer 对于python 3,必须根据此答案csv.writer添加newline=""

I am using Python 3.6 and it seems that 我正在使用Python 3.6 ,它似乎

csv.writer(open("test_step1.csv", "wb"), delimiter=",", newline="")

is not correct. 是不正确的。 Rather, newline="" should added in the open() clause. 相反,应在open()子句中添加newline=""

Please note that csv 1.0 in Windows (requires '\\n') and MAC OS (optional). 请注意Windows中的csv 1.0(需要'\\ n')和MAC OS(可选)。 The code below will output .csv file with no spaces between next line. 下面的代码将输出.csv文件,下一行之间没有空格。 It works in MAC and Windows. 它适用于MAC和Windows。

import csv
for i in range (5):
    MyList=[]
    MyList.append(i)
    cnword=0
    with open('test_step1.csv', 'a') as f:
        for item in MyList:
            if cnword != len(MyList)-1:
                f.write("%s," % item)
            else:
                f.write("%s" % item)
            cnword+=1

        f.write("\n" )  
    myList=[]

Just add newline='' where you are opening the file.只需在打开文件的位置添加 newline='' 即可。 It works for me.这个对我有用。 eg, csvFileName = open('file.csv', 'w', newline= '')例如,csvFileName = open('file.csv', 'w', newline= '')

"

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

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