'How can I create a loop with multiple assignment statements? [closed]

I have written a program that reads text files and then copy and pastes the content of each file, line by line, to a spreadsheet.

#! python3
# textFiles_to_spreadsheet.py - Reads in the contents of several text files
# and insert those contents into a spreasheet, with one line of text per row.
# The spreadsheet should look like that:
#
#     ----A----   ----B----   ----C----
# 1   file1Line1  file2Line1  file3line1
# 2   file1line2  file1line2  file3line2
# 3   file1line3  file1line3  file3line3
# etc.

import openpyxl

wb = openpyxl.Workbook()
sheet = wb.active

fileObj1 = open('c:/users/dell/ch13/textFile1.txt', encoding='UTF-8')
fileObj2 = open('c:/users/dell/ch13/textFile2.txt', encoding='UTF-8')
fileObj3 = open('c:/users/dell/ch13/textFile3.txt', encoding='UTF-8')
fileObj4 = open('c:/users/dell/ch13/textFile4.txt', encoding='UTF-8')
fileObj5 = open('c:/users/dell/ch13/textFile5.txt', encoding='UTF-8')

text1 = fileObj1.readlines()
text2 = fileObj2.readlines()
text3 = fileObj3.readlines()
text4 = fileObj4.readlines()
text5 = fileObj5.readlines()

content = [text1, text2, text3, text4, text5]

for i in range(1, 6):
    for j in range(1, len(content[i-1])+1):
        sheet.cell(column=i, row=j).value = content[i-1][j-1]

wb.save('c:/users/dell/ch13/text_to_spreadsheet.xlsx')
wb.close()

It's obvious that we have code fragments here that are repetitive and need to be simplified. The first thing that came to my mind is using for loops but then I stumbled over a new problem: The assignments are only valid inside the for loop, otherwise they are gone.

I need the variables to be valid even after the loop, so I can use them later for calling the readlines() method.

The code works, but I just don't see a nice way to simplify the repetitive lines of code with for loops.



Solution 1:[1]

you can declare variable with your base directory and empty list. in your loop every time you will pass to your list your file.

base_dir = "c:/users/dell/ch13/"
files = []

for x in range(5):
    files.append(open(f"{base_dir}yourfile{x}"))
after first loop you can access your file by referring to the index number

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 Mohamed Mehdawy