正如評論中提到的,這不是CSV格式,所以我必須制定解決方法。
def get_row_format(length_file):
with open(length_file, 'r') as fd_len:
#Read in the file, not a CSV!
#this double list-comprehension produces a list of lists
rows = [[x.strip() for x in y.split()] for y in fd_len.readlines()]
#determine the row-format from the rows lists
row_form = {int(x[0]): int(x[1]) for x in rows[1:]} #idx 1: to skip header
return row_form
def read_with_row_format(data_file, rform):
with open(data_file, 'r') as fd_data:
for row in fd_data.readlines():
#Get the formatted output
#use .items() for Python 3.x
formatted_output = [row[k-1:k+v-1] for k, v in rform.iteritems()]
print formatted_output
第一函數獲得「行格式」和第二函數應用於的行格式於每行的文件
用法中:
rform = get_row_format('lengths.csv')
read_with_row_format('data.csv', rform)
輸出:
['A', '1', '12', '34', '5', '6']
['B', '2', '12', '34', '5', '6']
['C', '3', '23', '45', '6', '7']
這哪裏是 「下面」?你忽略了包括你的編碼嘗試。另外請注意,這是*不是* CSV格式的文件;它似乎只是文字。 – Prune