我正在导入制表符分隔的文件。
import csv
with open(logfile) as f:
csvlines = csv.reader(f,delimiter='\t')
for row in csvlines:
print(row)
prints [' mike john steve']
有没有办法打印它
make|steve|john
我尝试使用csv.DictReader
,但由于它不是真正的csv文件,因此无法使用
答案 0 :(得分:1)
无法复制:
import csv
logfile = "t.txt"
with open(logfile,"w") as f:
f.write('mike\tjohn\tsteve\n')
f.write('mike john steve\n') # no tabs, just spaces
with open(logfile) as f:
csvlines = csv.reader(f,delimiter='\t')
for row in csvlines:
print(row)
输出:
['mike', 'john', 'steve']
['mike john steve']
在您....之前,您可能有一个用空格分隔的文件,因此所有文件都匹配到一栏中。
您可以通过以下方式解析以空格分隔的文件:
with open(logfile) as f:
csvlines = csv.reader(f,delimiter=' ', skipinitialspace=True)
for row in csvlines:
print(row)
Wich给您:
['mike\tjohn\tsteve'] # no spaces, all in one column
['mike', 'john', 'steve'] # multiple consecutive spaces = 1 column-divider