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时,每条记录后都会有一个额外的空白行!
有没有办法让它没有多余的空白?
在运行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,如下所示:
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)
为什么会发生这种情况,或者这实际上是期望的行为?
在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)