【问题标题】:Appending line to array in Python, String object has no attribute append在Python中将行附加到数组,String对象没有属性附加
【发布时间】:2015-01-27 05:36:54
【问题描述】:

我有两个文件,一个包含 4 列和多行 (input.xlxs),另一个包含 1 列和相同的行数 (rms_date.out)。我正在将 input.xlxs 中的行读取到数组中,并尝试在写入新文件之前将 rms_date.out 中的 1 行对应行附加到数组中。

当我尝试将 rms_date.out 中的行附加到数组时,我收到一个错误,表明该数组的类型为 String 并且没有附加方法,我很困惑:

    array[i].append(line)
AttributeError: 'str' object has no attribute 'append'

以下答案似乎表明我正在做的事情应该是可能的: https://stackoverflow.com/a/16222978/1227362 但是我显然做错了什么。上面的示例是否附加到数组对象本身,而我正在尝试附加到由循环确定的特定数组索引?抱歉,最近几天我才第一次使用 Python。

我的代码在这里(我还没有编写将附加数组写入新文件的位):

ins = open( "input.xlsx", "r" ) 
array = []
for line in ins:
    array.append(line)
file = open("rms_date.out", "r") 
for i in range(0, len(array)):
    for line in file:
        array[i].append(line)
        print array[i]
file.close()
ins.close()

请问有没有比上面概述的更简单的方法来执行我的建议?
谢谢,约翰!

【问题讨论】:

  • array[i] 是一个字符串 (line)。你不能 append 到一个字符串。
  • 字符串是不可变的。您可以使用+ 连接

标签: python arrays nested-loops import-from-csv


【解决方案1】:

嗯,字符串确实没有.append 方法,它们在python 中是不可变的。

您可以使用串联:

array[i] += line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2020-07-07
    • 1970-01-01
    • 2015-12-03
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多