I need to transfer the 1st line from a txt file to Column A then the 2nd line to Column B then 3rd line to Column C in the same row and then do it again for the next lines every 3 lines. every 3 lines is like 3 columns in 1 row.
My txt file looks like this:
7:52:01 AM sherr
hello GOOD morning .
おはようございます。
7:52:09 AM sherr
Who ?
誰?
7:52:16 AM sherr
OK .
わかりました。
enter image description here
I tried this code btw,
import pandas as pd
import openpyxl
file1 = open('chat_20220207131707.txt', 'r', encoding="utf8")
Lines = file1.readlines()
wb = openpyxl.Workbook()
ws= wb.worksheets[0]
x = 1
y = 1
if y < 4:
for row in Lines:
cell = ws.cell(row=x, column=y)
cell.value = row[0]
y = 1
else:
x = 1
y = 1
df.to_excel('sherrplease.xlsx', 'Sheet1', index=False)
CodePudding user response:
This should get you started (without using pandas):
from openpyxl import Workbook
wb = Workbook()
with open('chat_20220207131707.txt', encoding='utf-8') as sherr:
row = 0
ws = wb.active
for column, line in enumerate(sherr.readlines()):
if (c := column % 3 1) == 1:
row = 1
ws.cell(row=row, column=c, value=line.strip())
wb.save('sherrplease.xlsx')