如何创建包含多个赋值语句的循环?

How can I create a loop with multiple assignment statements?

我编写了一个读取文本文件的程序,然后将每个文件的内容逐行复制并粘贴到电子表格中。

#! 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()

很明显,我们这里有重复的代码片段,需要简化。我首先想到的是使用 for 循环,但后来我偶然发现了一个新问题:赋值仅在 for 循环内有效,否则它们就消失了。

我需要变量在循环后仍然有效,这样我可以稍后使用它们调用 readlines() 方法。

代码有效,但我只是没有找到使用 for 循环简化重复代码行的好方法。

您可以像这样将变量的所有路径转储到列表中:

    fileObj1 = 'c:/users/dell/ch13/textFile1'
    fileObj2 = 'c:/users/dell/ch13/textFile2'
    fileObj3 = 'c:/users/dell/ch13/textFile3'
    fileObj4 = 'c:/users/dell/ch13/textFile4'
    fileObj5 = 'c:/users/dell/ch13/textFile5'

    flist = [fileObj1, fileObj2, fileObj3, fileObj4, fileObj5]

现在可以调用for循环了:

    for file in flist:
        open(file)

您可以使用基本目录和空列表声明变量。 每次将文件传递给列表时都在循环中。

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

for x in range(5):
    files.append(open(f"{base_dir}yourfile{x}"))
在第一次循环后,您可以通过引用索引号

来访问您的文件