从文本文件中创建元组文本文件,每隔三行连续选择一次

时间:2017-05-01 02:14:07

标签: python tuples

我的文本文件包含以下数据:

AAA
111
A1A1
BBB
222
B2B2
CCC
333
C3C3

读取文本文件我需要创建包含元组的新文本文件:

(AAA,111,A1A1)
(BBB,222,B2B2)
(CCC,333,C3C3)

该函数必须连续选择每三行并从选择中创建元组。

3 个答案:

答案 0 :(得分:1)

我想你可以使用:

force: :cascade

Python Demo

答案 1 :(得分:1)

这会奏效。编写代码,以便包含信息的文件称为“source.txt”,并输出到名为“Output.txt”的文件。

OutputFile = open("Output.txt", 'w')
InputLines = open('source.txt', 'r').read().split("\n")


line = "("
for index in range(len(InputLines)):
    line += InputLines[index]
    if ((index+1) % 3 == 0): # if this is the third element
        OutputFile.write(line + ")\n")
        line = "(" # reinitialises the variable
    else:
        line += ", "

OutputFile.close()

答案 2 :(得分:0)

contentList = open('source.txt','r').readlines()
outFile = open('outfile.txt','w')

start , end , step = 0 , 3, 3 
while end <= len(contentList):
  eml1,eml2,eml3 = (contentList[start:end])
  writeString = '( '+eml1.rstrip('\n')+','+ eml2.rstrip('\n') +','+ eml3.rstrip('\n') +' )'
  outFile.write(writeString)
  outFile.write('\n')
  start = start + step
  end = end + step

outFile.close()

结果

# cat outfile.txt
( AAA,111,A1A1 )
( BBB,222,B2B2 )
( CCC,333,C3C3 )

# cat course.txt
AAA
111
A1A1
BBB
222
B2B2
CCC
333
C3C3