Jan-01-2023, 03:41 AM
Hi I have faced one problem I wish to read a text file, and when reaching ===== ending, I wish to write into a new separate sheet.
So for example, If I have a text file like below this:
datetime name department
20220101 James IT
20220101 Test IT
================
datetime name country
20220101 James US
20220101 Test US
================
So the default sheet1 will write like this:
datetime name department
20220101 James IT
20220101 Test IT
sheet2 will show
datetime name country
20220101 James US
20220101 Test US
How am I able to establish this result, the =====
I have a code but this only help me to write in a single sheet, but I wish after ==== it will write into a new sheet
So for example, If I have a text file like below this:
datetime name department
20220101 James IT
20220101 Test IT
================
datetime name country
20220101 James US
20220101 Test US
================
So the default sheet1 will write like this:
datetime name department
20220101 James IT
20220101 Test IT
sheet2 will show
datetime name country
20220101 James US
20220101 Test US
How am I able to establish this result, the =====
I have a code but this only help me to write in a single sheet, but I wish after ==== it will write into a new sheet
import openpyxl, string from openpyxl.utils import get_column_letter from openpyxl.styles import Font f = open('test.txt', 'r+') # open text excel = openpyxl.Workbook() sheet = excel.worksheets line = f.readline(); # read text while line: list = line.split() # convert if "=" in line: pass else: print(list123) if list [1] == 'userID': sheet[0].append(list ) # write into excel elif list [2] == 'name': sheet[0].append(list ) # write into excel else: sheet[0].append(list ) # write into excel line = f.readline() # read next line excel.save('result.xlsx')I try like this will occur error
from openpyxl.workbook import Workbook wb = Workbook() ws1 = wb.create_sheet("Sheet_A") ws1.title = "Title_A" f = open('test.txt', 'r+') # open text excel = openpyxl.Workbook() sheet = excel.worksheets line = f.readline(); # read text count =0 while line: list= line.split() # convert if list[1] == 'userID': ws1[0].append(list) # write into excel elif list[2] == 'name': ws1[0].append(list) # write into excel else: ws1.append(list) # write into excel line = f.readline() excel.save('test123.xlsx')