【发布时间】:2019-02-22 22:16:21
【问题描述】:
我是 Python(2.7.15) 的新手。我正在尝试将我的 Python 脚本的输出附加到一个由制表符分隔的文本文件中。
以下是我的部分代码:
for key,value in d.iteritems():
with open('output.txt', 'a') as file:
file.write(key + "\t" + value + "\t")
.....
....
for item in data["response"]["docs"]:
titleValue = (item['title'])
with open('/tmp/output.txt', 'a') as file:
file.write(titleValue + "\n")
我的输出文件如下所示:
FirstKey FirstValue
FirstTitle
SecondKey SecondValue
SecondTitle
基本上我想在同一行中将值打印为制表符分隔值,并将下一行打印为新行中的制表符分隔值,依此类推,如下所示:
FirstKey FirstValue FirstTitle
SecondKey SecondValue SecondTitle
我该怎么做? file.write 正在新行中打印它。我希望它在同一行打印
【问题讨论】:
-
没有时间(或 Python 2)来测试完整的答案,抱歉。但是,我认为您需要在单个
with open...中执行此操作。此外,研究for循环以了解如何同时迭代多个控件。 -
问题是我不能一次打开文件写入。我必须从两个不同的循环中获取输出,然后分别编写。
-
仔细观察,我看不出您展示的代码如何产生您展示的输出。我认为“SecondKey SecondValue”会出现在“FirstTitle”之前。
标签: python python-2.7 file