简体   繁体   English

如何读取文本文件格式并将其写入python中的以下格式中提到的excel文件中

[英]How to read the text file format and write the same in to excel file as mentioned in the below format in python

I want to read the data from the text file below and write it to an Excel sheet as explained further 我想从下面的文本文件中读取数据并将其写入Excel工作表,如进一步说明

在此处输入图片说明

The text file is formatted with each value on a new line. 文本文件被格式化,每个值都换行。

The Excel file should have Excel文件应具有

  • 'adobe' in row 0, column 1 第0行第1列中的“ adobe”
  • IE11.o to row 0, column 2 IE11.o到第0行第2列
  • 32 to row 0, column 3 32至第0行第3列

  • flash to row 1, column 1 闪烁至第1列,第1列

  • IE8.0 to row 1, column 2 IE8.0至第1列,第2列
  • 24 to row 1, column 3 24至第1列,第3列

and so on for many rows 以此类推

You probably want to read the text file, line by line, into a list . 您可能想逐行将文本文件读入list中 Then you can either export your data as a .csv file which excel can read, or directly as an excel file using a library like Openpyxl . 然后,您可以将数据导出为 excel可以读取的.csv文件 ,也可以使用Openpyxl之类的库直接将其导出为excel文件。

For example this code does what you've asked for, if you're happy to produce a .csv instead of an excel file: 例如,如果您愿意生成.csv而不是excel文件,则此代码可以满足您的要求:

fname = "" #path to file
csvname = "" #path to output csv

with open(fname) as f: #reads the file
    content = f.readlines() #writes lines to list
content = [x.strip() for x in content] #removes blank list values

names = content[0::3] #builds list of names
IEs = content[1::3] #builds list of IEs
numbers = content[2::3] #builds list of numbers

with open(csvname) as file: #creates csv file
    for i in range(len(content)/3): #runs through rows
        file.write(names[i]+","+IEs[i]+","+numbers[i]) #writing data to rows
        file.write('\n') #ends line after each row

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM