我要查找的目标或输出是将输入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)))
答案 0 :(得分: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]))
答案 1 :(得分:0)
你应该使用'r +'而不是'a +'。
``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.
{+ 3}}
讨论为什么+ +不起作用我无法更正f.write代码的缩进,所以这里是更正后的片段(注意用\ 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)))