python trim 选项卡来自文件
python trim tab from file
我正在导入一个制表符分隔的文件。
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 文件所以弄乱了
无法重现:
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']
您之前可能有一个 space 单独的文件....因此所有文件都匹配到一列中。
您可以通过以下方式解析 space 分隔的文件:
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
我正在导入一个制表符分隔的文件。
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 文件所以弄乱了
无法重现:
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']
您之前可能有一个 space 单独的文件....因此所有文件都匹配到一列中。
您可以通过以下方式解析 space 分隔的文件:
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