'How to write .xlsx data to a .txt file ensuring each column has its own text file, then each row is a new line?
I believe I am close to cracking this however I can't add multiple lines of text to the .txt files. The column do relate to their own .txt files.
import openpyxl
from pathlib import Path
# create workbook
wb = openpyxl.Workbook()
sheet = wb.active
listOfTextFiles = []
# Create a workbook 5x5 with dummy text
for row in range(1, 6):
for col in range(1, 6):
file = sheet.cell(row=row, column=col).value = f'text row:{row}, col:{col}'
listOfTextFiles.append(file)
print(listOfTextFiles) # for testing
wb.save('testSS.xlsx')
for i in range(row): # create 5 text files
textFile = open(f'ssToTextFile{i}.txt', 'w')
textFile.write(listOfTextFiles[i])
The output for each text file is below. I know it has something to do with the 'textFile.write(listOfTextFiles[i])' and I've tried many ways such as replacing [i] with [j] or [file]. I think I am overwriting the text through each loop.
Current output: ssToTextFile.txt -> text row:1, col:1
What I want the output to be in each .txt file:
ssToTextFile.txt -> text row:1, col:1
text row:2, col:1
text row:3, col:1
text row:4, col:1
text row:5, col:1
Then, the next .txt file to be:
text row:1, col:2
text row:2, col:2 etc
Would appreciate any feedback and the logic behind it please?
Solution 1:[1]
Solved. Using sheet.columns on the outer loop I could use [x-1] as the index.
for x in range(sheet.min_row, sheet.max_row + 1):
textFile = open(f'ssToTextFile{x-1}.txt', 'w')
for y in list(sheet.columns)[x-1]:
textFile.write(str(y.value)+ '\n')
print(y.value)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Luca |