【发布时间】:2020-11-20 02:22:34
【问题描述】:
如何读取 txt 文件,使用 for 循环将该 txt 文件的列表存储在变量列表中,然后打印变量列表?
这是输出变量列表的代码。我正在寻找保存 将名为 score 的 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
【问题讨论】:
-
我对 python 不是很擅长,但在半天后,我有了一个 csv 阅读器,它可以读取 numpy 列表并将它们转换为“Pandas”数据帧并对其进行一些统计。尤其是寻找有关 csv 读入 Pandas 的示例。似乎是您需要的一切。
-
这能回答你的问题吗? Python read .txt File -> list
-
是的,这回答了我的问题
标签: python python-3.x list for-loop text-files