如何读取 txt 文件,使用 for 循环将该 txt 文件的列表存储在变量列表中,然后打印变量列表?

How to read a txt file, store the list of that txt file in a variable list using a for loop and then print the variable list?

如何读取 txt 文件,使用 for 循环将该 txt 文件的列表存储在变量列表中,然后打印变量列表?

这是输出变量列表的代码。我正在寻找保存 将名为 scores 的 txt 文件中的行转换为变量列表。然后打印 变量列表

 Scores = open("scores","r")
 ** I use this line to read the scores function **
  
Scores = []
** This is the variable list I am going to store the txt file in by 
  using the for loop to go through each line in 'scores'**
  
  for line in Scores:
** takes the first line of the txtfile scores **
      
      line = line.strip()
 ** removes whitespace of that line.**
      
      Scores.append(line)
 ** Then adds that line to the variable list Scores ** 
     
     Scores.close()
 ** stops once the list hasn't gone through each line in the txt 
file ands stored in the variable list.**

print(Scores)
** suppose to print the value of scores in a list** 

output=[]
** however my output is []**

** Desired output example = Scores [ 'A 1' , 'B 3' ... etc] **
 



if this helps with context, the textfile scores is:
A 1
B 3
C 5
D 3
E 1
F 5
G 4
H 3 
I 1
J 10
K 8
L 3
M 5
N 3
O 2
P 5
Q 20
R 3
S 3
T 2
U 1
V 10
W 12
X 16
Y 8
Z 20

您可以通过创建一个循环遍历并添加每一行的函数来做到这一点:

def read_txt(file):
    scores = []
    with open(file, 'r') as input_file:
        for line in input_file.readlines():
            line = line.replace("\n", "")
            scores.append(line)
    return scores

解释:

scores = []

这将创建一个名为 scores 的新列表。

with open(file, 'r') as input_file:

上面这行代码用于打开需要的文件,并赋值给变量input_file.

for line in input_file.readlines():
    line = line.replace("\n", "")
    scores.append(line)

这遍历每一行代码,删除所有换行符 \n 并将其附加到列表 scores。 运行 该函数使用以下代码行:

print(read_txt(What file you want to use goes here))

尝试将您的代码更新为此。

with open("scores.txt","r") as file:
    scores = [line.strip().replace('\n','') for line in file.readlines()]
print(scores)