简体   繁体   English

将 txt 文件读入 python 中的列表

[英]Reading a txt file into a list in python

I just started to learn python and I was wondering how to read a bunch of numbers from a txt file and put it into a sort of list.我刚开始学习 python,我想知道如何从 txt 文件中读取一堆数字并将其放入某种列表中。 The txt file I want to read has three numbers next to each other with a space in between.我要读取的 txt 文件有三个相邻的数字,中间有一个空格。

Like this:像这样:

24 39 45\n

I want to read this file into a list: [24, 39, 45]我想将此文件读入列表: [24, 39, 45]

How can I do that?我怎样才能做到这一点? The .readlines() method doesn't seem to work as it turns the whole line into one single element: list[0] = ['24 39 45\n'] . .readlines()方法似乎不起作用,因为它将整行转换为一个元素: list[0] = ['24 39 45\n']

Pardon me if this sounds like a stupid question.如果这听起来像一个愚蠢的问题,请原谅我。 This is my first question here.这是我在这里的第一个问题。 Thank you!谢谢!

.readLine().split()

It reads the full line, and uses split to separate it into space-separated values.它读取整行,并使用 split 将其分隔为空格分隔的值。

You should use .read().splitlines() to first get a list where each element looks like ['24 39 45'] then, a .map with a .split to split each of those by space.您应该使用.read().splitlines()首先获取一个列表,其中每个元素看起来像['24 39 45']然后,一个带有.split.map以按空格分割每个元素。

with open(filename, 'r') as textfile:
    content = textfile.read().splitlines()
content = list(map(lambda x: x.split(' '), content))

Output-输出-

[['24', '39', '45'], ['52', '42', '39']]

Where textfile was-文本文件在哪里-

24 39 45 24 39 45

52 42 39 52 42 39

This will return a list of lists, where each element will be a list of numbers这将返回一个列表列表,其中每个元素都是数字列表

try the code follows试试下面的代码

g = open("demofile.txt", 'r')
step1=g.readlines()
step2=[]
for a in step1:
    step2.append(a.split())
print(step2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM