以前曾询问过这种情况的变体,但文件 I/O 的处理在 Python 2 和 3 之间发生了显着变化,而且我还没有找到任何有效的方法。
我的环境是 Windows 上的 Python 3.4.1
csv 文件(例如由 Excel 生成的文件)可以包含多行带引号的字符串,这些字符串可以在单个字段中包含换行符(十六进制 0A)。如何正确解析这些内容而不是将其解释为输入行的末尾?
下面是一个包含两行(除了标签行之外)的示例 .csv 文件。如果重要的话,我可以以 utf-8 或 utf-16 格式获取输入:
Column 1 Column 2
12345 single line of text
23456 "text with a newline here >
< that should remain in one cell"
Run Code Online (Sandbox Code Playgroud)
这段代码:
reader = csv.reader(open('Test.csv', newline=''), skipinitialspace = True)
for row in reader:
print(', '.join(row))
Run Code Online (Sandbox Code Playgroud)
产生这样的结果:
Column 1, Column 2
12345, single line of text
23456, text with a newline here >
< that should remain in one cell
Run Code Online (Sandbox Code Playgroud)
预先感谢您可以提供的任何帮助。
| 归档时间: |
|
| 查看次数: |
1579 次 |
| 最近记录: |