我正在从常规文本文件中读取一些行并将它们附加到列表中。有时,此列表会合并为单元素列表并写入 CSV 文件。但是,有时我会看到写出的数据在某个任意点过早地被切断,即其余数据丢失。如果我在写入文件之前将此列表打印到控制台,我可以看到所有数据都清楚地存在,所以我认为这是我的代码中的一些格式或 IO 问题。我做错了什么?
with open(out_fname, 'wb') as fout:
csv_out = csv.writer(fout)
csv_out.writerow(header_list)
with open(in_fname, 'rb') as fin:
for _ in xrange(data_start_row-1):
next(fin)
for line in fin:
#find identifier for row of interest
if re.search(regex_id, line):
#parse out first parameter
match1 = re.search(regex_m1, line)
if match1: csv_out_l.append(match1.group(1))
#parse out second parameter
match2 = re.search(regex_m2, line)
if match2: csv_out_l.append(match2.group(1))
#parse out third parameter
match3 = re.search(regex_m3, line)
if match3: csv_out_l.append(match3.group(1))
#remove all newline elements in rest of log info
log_info = [element for element in log_info if element != '\n']
#remove all newline char's in elements
log_info = map(lambda s: s.strip(), log_info)
log_info = ["\n".join(log_info)]
csv_out.writerow(csv_out_l + log_info)
#clear lists
csv_out_l[:] = []
log_info[:] = []
#skip next line which does not contain useful info
next(fin)
#otherwise store general data in the meantime
else:
log_info.append(line)
最佳答案
抱歉,我意识到这不是 Python 问题。这与 Excel 不喜欢我的某些 CSV 输出行以等号 (=) 开头这一事实有关。我想 Excel 认为这是一个公式并在限制后截断字符。如果我在开头添加一个撇号,那么一切都会正常。
关于python - CSV writer 切断一些写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46490672/