2 подходов:
(вы также можете продолжить без csv.reader
, просто разделите на sep
с конечными пробелами)
Примеры файлов:
pipe.txt:
Bouillon | Francis | G | M | Blue | 6-3-1975
a | b | c | d | f | g
comma.txt:
Bouillon , Francis , G , M , Blue , 6-3-1975
a , b , c , d , f , g
space.txt
Bouillon Francis G M Blue 6-3-1975
a b c d f g
import csv
from itertools import chain
with open('pipe.txt') as f:
line = next(f).strip() # extracting the 1st line
sep = re.search(r'^\w+([\s\|,]+)', line).group(1)
sep = ' ' if sep.isspace() else sep.strip()
reader = csv.reader(chain(iter([line]), f), delimiter=sep, skipinitialspace=True)
for row in reader:
print(row)
Вывод (для файла comma.txt
и pipe.txt
):
['Bouillon ', 'Francis ', 'G ', 'M ', 'Blue ', '6-3-1975']
['a ', 'b ', 'c ', 'd ', 'f ', 'g']
with open('space.txt') as f:
...
Выход для space.txt
более чистый благодаря функции skipinitialspace=True
:
['Bouillon', 'Francis', 'G', 'M', 'Blue', '6-3-1975']
['a', 'b', 'c', 'd', 'f', 'g']
или без csv.reader
:
with open('comma.txt') as f:
line = next(f).strip()
sep = re.search(r'^\w+([\s\|,]+)', line).group(1)
pat = re.compile(sep)
for row in chain(iter([line]), f):
print(pat.split(row.strip()))
Выход:
['Bouillon', 'Francis', 'G', 'M', 'Blue', '6-3-1975']
['a', 'b', 'c', 'd', 'f', 'g']
Наслаждайтесь!