【问题标题】:conditionally write in array有条件地写入数组
【发布时间】:2016-08-22 20:59:44
【问题描述】:

我有一段代码可以检查并打开几个制表符分隔的文件。每次打开文件的第一个选项卡以四个数字开头(例如 0012)时,我想将这一行写入一个数组(逐个单元格)。

我想传输到数组的示例行如下所示:

0029 Montana 1970 0922 1133 5.4 CR 620 Eagle 31.9 CAA - 1.10

可以看出,在某些情况下,选项卡将带有“-”。我希望将其转移。我知道我应该像这样开始:

with open(each_file) as f:
   for line in f:

但之后我需要一些帮助

【问题讨论】:

  • 澄清点:Python 的标准可变序列类型是 list,而不是 array(有一个 array 模块,但这是一个特殊用途的模块,用于需要存储大量数字适合有限精度 C 类型的数据)。

标签: python python-3.x csv


【解决方案1】:

使用the csv module;它supports tab separated dialects 很好。例如:

import csv

with open(each_file, newline='') as f:
   for row in csv.reader(f, dialect='excel-tab'):
       # On each iteration row is a list containing the fields from a single record
       # properly splitting only on tabs, not spaces, and handling the Excel
       # standard quoting rules when a field might contain tabs or newlines

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2014-09-16
    • 2019-06-01
    • 2018-08-16
    • 2021-05-01
    • 2021-12-22
    相关资源
    最近更新 更多