如何阅读使用Python的文本文件中的数字? [英] How to read numbers in text file using python?

查看:141
本文介绍了如何阅读使用Python的文本文件中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python编程的新手,我正在通过简单的程序学习python。这是我想要做的:如果我有一个文本文件包含数字:
说这个f1.txt

 <$ c $ 
$ b 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 15


fp = open('f1.txt')
a1 = []
a2 = []
a3 = []
a4 = []
lines = fp.readlines()

for ln in lines [0:len(lines)]:
line = ln.strip().span()
a1 = line ();

fp.close()

我想在a1中获得第一列,a2中的第二个等等。我知道上面的代码可能是错误的,请告诉我哪里出了错,如何纠正。特别是我不理解命令'ln.strip()。split()'。有人可以帮忙吗?

解决方案

您可以这样做:



<$ ('')
a1 = [code a1 = []
a2 = []
a3 = []
a4 = [] f1.txt')作为f:
在f:
data = line.split()
a1.append(int(data [0]))
a2。 append(int(data [1]))
a3.append(int(data [2]))
a4.append(int(data [3]))
和语句来打开文件。这确保即使出现错误时文件也会自动关闭。这样更好。当文件打开的时候 f 将成为文件句柄。



现在,Python允许我们遍历行简单地通过遍历文件句柄。因此, for f 中的行将自动迭代所有行。没有必要首先调用 readlines(),当然不需要执行 lines [0:len(lines)] 它基本上只创建一个列表的副本 - 你可以迭代



现在里面的循环中,我们接下来的行,并用空格分隔 - 没有参数 str.split 将始终这样做。 str.split 返回一个列表,所以我们将其存储在一个额外的变量。接下来,我们将每列添加到正确的列表。而当你想把值作为数字,我们将它们转换为整数。



str.strip 基本上是取消了字符串的前导或尾随空格。因为我们使用 str.split 没有参数,所以额外的空格也会被删除,所以我们并不需要这个。


$ b $最后,有四个单独的列表存储在单独的变量是有点烦人维护。你可以简单地创建一个列表清单,而不是:

pre $ a $ [],[],[],[]]#一个包含四个空列表的列表

然后,在循环内部,可以添加<$ c



$ b $ $ $ $ $ $ $ $ $ $ > for i,枚举值(line.split()):
a [i] .append(int(value))

当遍历 枚举 ,你不仅会得到值(当你迭代列表时),还会得到索引。因此,使用这个,我们得到了每个元素在分割线中的索引,并且可以自动地将它附加到 a 的正确子列表中。


I am new to python programming and I am learning python by doing simple programs. Here is what I would like to do: if I have a text file containing numbers: say this a f1.txt

f1.txt:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 15


fp = open('f1.txt')
a1=[]
a2=[]
a3=[]
a4=[]
lines = fp.readlines()

for ln in lines[0:len(lines)]:
line=ln.strip().split()
a1=line();

fp.close()

I want to get first column in a1, second in a2 and so on. I know above code may be wrong, please tell me where I went wrong and how to correct it. Especially I am not understanding command 'ln.strip().split()'. Can someone help?

解决方案

You could do it like this:

a1 = []
a2 = []
a3 = []
a4 = []

with open('f1.txt') as f:
    for line in f:
        data = line.split()
        a1.append(int(data[0]))
        a2.append(int(data[1]))
        a3.append(int(data[2]))
        a4.append(int(data[3]))

So first of all, we use the with statement to open the file. This makes sure that the file is automatically closed even when errors appear. It’s just nicer that way. While the file is open f will be the file handle.

Now, Python allows us to iterate over the lines of a file simply by iterating over the file handle. So for line in f will iterate over all lines automatically. There is no need to call readlines() first, and certainly no need to do lines[0:len(lines)] which essentially only creates a copy of the list—you could just iterate over lines too.

Now inside of the loop, we take the line, and split it by whitespace—without arguments str.split will always do that. str.split returns a list, so we store that in an extra variable. Next we append each column to the correct list. And as you want the values as numbers, we convert them to integers.

The str.strip you mentioned basically takes off any leading or trailing whitespace of the string. As we are using str.split without arguments, extra whitespace will be removed too, so we don’t really need that.

Finally, having four separate lists stored in separate variables is a bit annoying to maintain. You could simply create a list of lists instead:

a = [[], [], [], []] # A list with four empty lists

And then, inside of the loop, you can just append data[i] to a[i]:

for i, value in enumerate(line.split()):
    a[i].append(int(value))

When iterating over enumerate, you will not only get the value (which you would get when iterating just over the list), but also the index. So using this, we get the index of each element within the splitted line and can automatically append it to the correct sublist of a.

这篇关于如何阅读使用Python的文本文件中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆