【发布时间】:2016-06-06 10:53:59
【问题描述】:
我有一个 tsv 文件(制表符分隔),并且想在将大量数据导入到 postgresql 数据库之前使用 python 过滤掉大量数据。 我的问题是我找不到保留原始文件格式的方法,这是强制性的,否则导入过程将无法正常工作。 网络建议我应该使用 csv 库,但无论我使用什么定界符,我最终都会得到与原始格式不同的文件,例如。 G。文件,在每个字符后包含一个逗号或文件,在每个字符后包含一个制表符,或在一行中包含所有数据的文件。 这是我的代码:
import csv
import glob
# create a list of all tsv-files in one directory
liste = glob.glob("/some_directory/*.tsv")
# go thru all the files
for item in liste:
#open the tsv-file for reading and a file for writing
with open(item, 'r') as tsvin, open('/some_directory/new.tsv', 'w') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
# I am not sure if I have to enter a delimter here for the outfile. If I enter "delimter='\t'" like for the In-File, the outfile ends up with a tab after every character
writer = csv.writer(csvout)
# go thru all lines of the input tsv
for row in tsvin:
# do some filtering
if 'some_substring1' in row[4] or 'some_substring2' in row[4]:
#do some more filtering
if 'some_substring1' in str(row[9]) or 'some_substring1' in str(row[9]):
# now I get lost...
writer.writerow(row)
你知道我做错了什么吗?最终文件必须在每个字段之间有一个制表符,并在末尾有某种换行符。
【问题讨论】:
-
# I am not sure if I have to enter a delimter here for the outfile.: 是的,你应该这样做,否则它将使用默认分隔符! -
docs.python.org/2/library/csv.html#csv.writer 参见
delimiter参数到writer(...)。
标签: python postgresql csv