将列表转换为字符串时出错

时间:2014-03-17 17:51:32

标签: python string list csv

我正在尝试指定我希望将数据写入输出文件的位置,但是我收到以下错误。我可以告诉我如何解决这个问题吗?

Traceback (most recent call last):
  File "C:/Python33/Upstream and downstream shores.py", line 20, in <module>
    upstream_shore.writerow (line[0] + [upstream_1] + line[1])
TypeError: Can't convert 'list' object to str implicitly

这是我的代码:

import csv

file1 = open ('fileA.csv', 'rt', newline ='')
reader = csv.reader(file1)

upstream = open ('fileB.csv', 'wt', newline = '')
upstream_shore = csv.writer(upstream)

downstream = open ('fileC.csv', 'wt', newline = '')
downstream_shore = csv.writer(downstream)

count_upstream = 0
count_downstream = 0

for line in reader:
    downstream = [(int(x) - 2000) for x in line[2]]
    upstream = [(int(y) - 2000) for y in line [1]]
    upstream_1 = str(upstream)
    downstream_1 = str(downstream)
    upstream_shore.writerow (line[0] + [upstream_1] + line[1])
    count_upstream += 1
    downstream_shore.writerow(line[0] + line [2] + [downstream_1])
    count_downstream += 1

 print ('Number of upstream shore counts:', count_upstream)
 print ('Number of downstream shore counts:', count_downstream)

file1.close()
upstream.close()
downstream.close()

由于

2 个答案:

答案 0 :(得分:0)

在以下行中:

upstream_shore.writerow (line[0] + [upstream_1] + line[1])

line[0](和line[1])是一个字符串,而不是列表。 Python正在尝试连接一个字符串和一个列表,但它不知道如何为它提供TypeError。您可能需要[line[0]],以便它连接2个列表(知道该怎么做),例如:

upstream_shore.writerow ([line[0]] + [upstream_1] + [line[1]])

注意,你会再次出现相同的错误2行。

答案 1 :(得分:0)

您正在添加line[0],这是一个包含[upstream_1]的字符串,这是一个列表。您应该使用[line[0]]创建只包含一个项目的列表。

upstream_shore.writerow ([line[0]] + [upstream_1] + [line[1]])