【问题标题】: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 文件的列表存储在变量列表中,然后打印变量列表?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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))
    

    【讨论】:

    • 他们没有输出,编译器跳过代码
    • 你必须通过print(read_txt(what file you want to use goes here))运行函数
    • 感谢您的帮助
    猜你喜欢
    • 2020-08-30
    • 2016-10-24
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多