【问题标题】:Python: append split list is emptyPython:追加拆分列表为空
【发布时间】:2016-05-22 13:52:17
【问题描述】:

我正在寻找的目标或输出是将现有输入文件的所有行的第一部分附加到输入 txt 文件。举个例子:

Input:
line_item1 string1
line_item2 string2
line_item3 string3

Output:
line_item1 string1
line_item2 string2
line_item3 string3
line_item1   # append
line_item2   # append
line_item3   # append

我创建的代码没有输出任何东西:

portionA = []
with open('output outfile.txt', "a+") as f:
    for line in f.readlines():
        parts = line.strip().split("\t", 1)
        portionA = parts[0]
        portionB = parts[1]
        portionA.append(line)
        f.write('{}\n'.format(''.join(portionA)))   

【问题讨论】:

  • 这还不清楚。你能提供一些实际的例子吗? “选定的行”是什么意思?
  • 我看到您想在末尾附加相同的行。删除了我的答案
  • @user1739581 仔细想想,我的直觉确实是对的。已取消删除并更新了我的答案。请看一下

标签: python list python-2.7


【解决方案1】:

你可以试试:

with open('output outfile.txt', "a+") as f:
    for line in f.readlines():
        parts = line.strip().split("\t")
        f.write('{}\n'.format(parts[0])) 

【讨论】:

    【解决方案2】:

    您应该使用“r+”而不是“a+”。

    ``r+''  Open for reading and writing.  The stream is positioned at the
             beginning of the file.
    

    讨论了为什么 a+ 不起作用here

    我无法更正 f.write 代码中的缩进,所以这里是更正后的 sn-p(注意用 \n 连接而不是空字符串)

    writeList= []
    with open('outfile.txt', "r+") as f:
        for line in f:
            parts = line.strip().split("\t", 1)
            portionA = parts[0]
            portionB = parts[1]
            writeList.append(line)
        f.write('{}\n'.format('\n'.join(writeList)))
    

    【讨论】:

    • 这作为评论会更好。
    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2012-08-30
    • 2018-11-23
    • 2020-07-28
    • 2023-03-11
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多