Txt列表分隔列

2024-09-23 22:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个txt文件中的一列中存储了一组数据,如下所示:

name1
address1
number1
name2
address2
number2
name3
address3
number3
name4
address4
number4

等等

我想把它分成3列,这样就可以导入excel了

有什么线索吗


Tags: 文件数据txtname1name2name3number1number2
3条回答

这应该做到:

infile = open("data.txt","r")

outfile = open("Excel.csv","w")

while True:
    name = infile.readline().strip()
    address = infile.readline().strip()
    number = infile.readline().strip()

    data = ','.join([name,address,number])
    if data == ",,":
        break

    data += '\n'
    outfile.write(data)

如果我记得我在Excel的时候,CSV做得很好

你可以用Microsoft word来做

将数据粘贴到MSWord中(作为keep text only),然后将它们全部选中(Ctrl+A)。转到insert功能区。从Table按钮,选择convert text to table

选择number of columns3并选择separate text at作为Paragraph

它会给你确切的输出你想要的。不需要对你遇到的每件事都进行编码。您可以阅读更多关于它的信息here

你可能想要这样的东西:

with open("input.txt", "r") as infile:

  line = infile.read().split()
  line = [" ".join(line[i:i+3]) for i in range(0,len(line),3)]
  print(line)

  with open("output.txt", "w") as outfile:
    for i in line:
      outfile.write(i + "\n")

output.txt的内容:

name1 address1 number1
name2 address2 number2
name3 address3 number3
name4 address4 number4

相关问题 更多 >