Python在CSV文件中的新行混淆 [英] Python New Line confusion in a CSV file

查看:117
本文介绍了Python在CSV文件中的新行混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Python代码。它读取一个csv文件,并输出第一列到一个新的csv文件。

I have the following Python code. It reads a csv file and outputs the first column to a new csv file.

但问题是在我的csv文件有\\\
除了新行创建新行。但他们被包裹在双引号内。

But the problem is in my csv file there is \n apart from new lines for creating new rows. But they are wrapped within a double quote.

例如:

A, B, C,
D, "12
34", E,
F, G, H

所以我想我需要添加quotechar =''在某个地方,但我不能弄清楚。

So I think i need to add quotechar='"' somewhere but I couldnt figure it out.

f_in = open('source.csv')

fields = []

for line in f_in.readlines():
    fields.append([item.strip('\n') for item in line.split(',')])
f_in.close()

f_out = open('sourceNew.csv', 'w')

for i in range(len(fields)):
    if fields[i][0] != '':
        f_out.write(fields[i][0] + ',,\n')


f_out.close()

如何区分包含在双引号中的真实新行\\\
和\\\

How can i distinguish the real new row \n and \n wrapped in a double quote.

感谢

推荐答案

使用 Python CSV 模块:

import csv

records = []
reader = csv.reader(open('source.csv', 'rb'))

for record in reader:
    print record
    records.append(record)

我希望这有助于。

这篇关于Python在CSV文件中的新行混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆