我们正在从一个大的csv文件创建一个子文件。子文件仅包含那些第一列的值为D1的行:
import csv
with open('input.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter='|', quotechar='|')
writer1 = csv.writer(open('output.csv', 'w'), delimiter = ' ')
for row in reader:
a = row[0]
row = '|'.join(row)
if (a=='D1'):
writer1.writerow(row)
此代码提供了两个问题:
"H e l l o"
。答案 0 :(得分:1)
此代码运行良好:
import csv
with open('input.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter='|', quotechar='|')
writer1 = csv.writer(open('output.csv', 'wb'), delimiter = '|')
for row in reader:
a = row[0]
if (a=='D1'):
writer1.writerow(row)
感谢Pedru
答案 1 :(得分:0)
来自python csv docs ..
import csv with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
所以看来你必须使用['Spam']
列表spamwriter.writerow
...如果它不是列表,这个方法writerow
正在从可迭代输入创建自己的列表,如下所示: / p>
>>> a = 'ala ma kota'
>>> list(a)
['a', 'l', 'a', ' ', 'm', 'a', ' ', 'k', 'o', 't', 'a']