我正在尝试创建一个与3个不同文本文件组合在一起的新文本文件。我会用代码提供更多细节。
text a file = z
a
y
text b file = s
x
d
text c file = 1
3
2
所以有a,b,c文本文件,我想做:
text newfile: z s 1
y d 2
a x 3
如上所示,我希望newfile按'C'文件的顺序排列。 以下是我的成就。
def main():
a = open("text1","r")
b = open("text2","r")
c = open("text3","r")
text1list = []
text2list = []
text3list = []
for line1 in a:
line1 = line1.strip()
text1list.append(line1)
for line2 in b:
line2 = line2.strip()
text2list.append(line2)
for line3 in c:
line3 = line3.strip()
text3list.append(line3)
aa,bb,cc = zip(*sorted(zip(text3list, text1list, text2list)))
combine = list(zip(bb,cc,aa))
with open("finalfiles", 'w') as zzzz:
for item in combine:
zzzz.write("{}\n".format(item))
问题是,现在,我的输出是
('z','s','1')
('y','d','2')
('a','x','3')
我的分类工作正常,但它与我的预期不同。 我不想要那些''和()。我想是因为那些是名单......? 我陷入了困境。 另外,请告诉我,我的排序看起来很好!
答案 0 :(得分:1)
您的combine
变量是元组列表。加入每个元组(item
)并写入文件
zzzz.write(" ".join(item))
您的代码有点缩短和DRY版本:
files = ["text1", "text2", "text3"]
groups = []
for each_file in files:
with open(each_file, 'r') as fo:
groups.append(sorted(fo.read().split('\n')))
with open("finalfiles", 'w') as out_file:
for each_group in zip(*groups):
out_file.write("{} {} {}\n".format(*each_group))