相关疑难解决方法(0)

用Python编写的CSV文件在每行之间都有空行

import csv

with open('thefile.csv', 'rb') as f:
  data = list(csv.reader(f))
  import collections
  counter = collections.defaultdict(int)

  for row in data:
        counter[row[10]] += 1


with open('/pythonwork/thefile_subset11.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in data:
        if counter[row[10]] >= 504:
           writer.writerow(row)
Run Code Online (Sandbox Code Playgroud)

此代码读取thefile.csv,进行更改并将结果写入thefile_subset1.

但是,当我在Microsoft Excel中打开生成的csv时,每条记录后都会有一个额外的空白行!

有没有办法让它没有多余的空白?

python windows csv

394
推荐指数
7
解决办法
24万
查看次数

Python 3.3 CSV.Writer写入额外的空白行

在Windows 8上使用Python 3.3,当写入CSV文件时,我收到错误TypeError: 'str' does not support the buffer interface并使用了"wb"标志.但是当只使用"w"标志时,我没有错误,但是每一行都被一个空行隔开!

问题写作

test_file_object = csv.reader( open("./files/test.csv", 'r') )
next(test_file_object )

with open("./files/forest.csv", 'wb') as myfile:
    open_file_object = csv.writer( open("./files/forest.csv", 'wb') )
    i = 0
    for row in test_file_object:
        row.insert(0, output[i].astype(np.uint8))
        open_file_object.writerow(row)
        i += 1
Run Code Online (Sandbox Code Playgroud)

错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-121-8cbb94f602a8> in <module>()
      8     for row in test_file_object:
      9         row.insert(0, output[i].astype(np.uint8))
---> 10         open_file_object.writerow(row)
     11         i += 1

TypeError: 'str' does not …
Run Code Online (Sandbox Code Playgroud)

python csv python-3.x

19
推荐指数
2
解决办法
2万
查看次数

在Python中编写.CSV文件,适用于Windows中的Python 2.7+和Python 3.3+

编辑:我把它放在标题中,但只是意识到我没有在体内提到它.这似乎是Windows特有的.

我很难csv在一个兼容Python 2.7和3.3的脚本中使用Python模块编写输出.

第一次尝试在Python 2.7中按预期工作:

with open('test.csv', 'wb') as csv_file:
    writer = csv.DictWriter(csv_file, ['header1', 'header2'])
    writer.writeheader()
    for item in items:
        writer.writerow(item)
Run Code Online (Sandbox Code Playgroud)

但是,当在Python 3.3中运行同样的事情时,你最终得到:

TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)

所以我改变'wb''wt'它运行,但现在我有一个额外的空白行中的文件每隔一行.

为了解决这个问题,我改变了:

with open('test.csv', 'wt') as csv_file:
Run Code Online (Sandbox Code Playgroud)

至:

with open('test.csv', 'wt', newline='') as csv_file:
Run Code Online (Sandbox Code Playgroud)

但现在,它打破了Python 2.7:

TypeError: 'newline' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

try:
    with open('test.csv', 'wt', newline='') as csv_file:
        writer = csv.DictWriter(csv_file, ['header1', 'header2'])
        writer.writeheader()
        for item in …
Run Code Online (Sandbox Code Playgroud)

python csv python-2.7 python-3.x python-3.3

15
推荐指数
2
解决办法
2万
查看次数

标签 统计

csv ×3

python ×3

python-3.x ×2

python-2.7 ×1

python-3.3 ×1

windows ×1