【发布时间】:2017-06-21 08:30:36
【问题描述】:
输入文件是标准的 CSV 文件,大约有 200 行和 70 列。
我需要根据架构重命名标题,将其写入新文件并从原始文件追加数据。
但是,某些字段包含多行文本,当我使用 next(file) 省略原始标题时,单个字段中的这些行被解释为新的 CSV 行(见下文)
原始文件示例:
+----------------+-----------+----------+-----------+------------------+-----------+
| Summary | Issue key | Issue id | Parent id | Issue Type | Status |
+----------------+-----------+----------+-----------+------------------+-----------+
| Project info 2 | ABCDE | 326974 | NA | Approval Request | Completed |
| info continues | | | | | |
| in signle cell | | | | | |
+----------------+-----------+----------+-----------+------------------+-----------+
输出后的文件:
+================+===========+=========+===========+==================+===========+
| Summary | Issue key | Renamed | Parent id | Renamed | Status |
+================+===========+=========+===========+==================+===========+
| Project info 2 | ABCDE | 326974 | NA | Approval Request | Completed |
+----------------+-----------+---------+-----------+------------------+-----------+
| info continues | | | | | |
+----------------+-----------+---------+-----------+------------------+-----------+
| in single cell | | | | | |
+----------------+-----------+---------+-----------+------------------+-----------+
最后,这是代码:
with open(self.paths['raw_file_path'], "r", encoding='UTF-8', errors="ignore") as cut_file:
header = cut_file.readline().strip()
# header renaming code, works well
with open(self.paths['head_file_path'], "w", encoding='UTF-8',) as head_file:
head_file.write(",".join(header))
next(cut_file)
for line in cut_file:
head_file.write(line)
当我在没有next() 的情况下每行转储文件时,一切都是正确的。但是,我需要跳过第一行(原始标题)。
感谢您的帮助!
【问题讨论】:
-
使用 csv 模块。
标签: python csv file-io python-3.4