相关疑难解决方法(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中的CSV在Windows上添加额外的回车符

在运行Windows XP专业版的Python 2.7中:

import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()
Run Code Online (Sandbox Code Playgroud)

它生成一个文件test.csv,每行有一个额外的\ r \n,如下所示:

test.csv

hi,dude\r\r\nhi2,dude2\r\r\n
Run Code Online (Sandbox Code Playgroud)

而不是预期的:

hi,dude\r\nhi2,dude2\r\n
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,或者这实际上是期望的行为?

python windows csv newline

202
推荐指数
4
解决办法
14万
查看次数

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万
查看次数

标签 统计

csv ×3

python ×3

windows ×2

newline ×1

python-3.x ×1