conditionally write in array

python python-3.x csv

30 просмотра

1 ответ

92 Репутация автора

I have a piece of code that goes through and open several tab-delimited files. Each time the first tab of the line of this opened file starts with four numbers (ex. 0012) I would like to write this line in an array (cell-by-cell).

A sample line that I would like to transfer to an array is shown below:

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

As can be seen in some cases the tab will have "-". I would like that to be transferred. I know I should start like:

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

but I need some help with afterwards

Автор: Kostas Belivanis Источник Размещён: 22.08.2016 08:59

Ответы (1)

1 плюс

75332 Репутация автора

Use the csv module; it supports tab separated dialects just fine. For example:

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
Автор: ShadowRanger Размещён: 23.08.2016 01:37
Вопросы из категории :