简体   繁体   English

使用 readline()?

[英]Use of readline()?

I have a question about this program:我有一个关于这个程序的问题:

%%file data.csv 
x1,x2,y
0.4946,5.7661,0
4.7206,5.7661,1
1.2888,5.3433,0
4.2898,5.3433,1
1.4293,4.5592,0
4.2286,4.5592,1
1.1921,5.8563,0
3.1454,5.8563,1

f = open('data.csv')
data = []
f.readline()
for line in f:
  (x1,x2,y) = line.split(',')
  x1 = float(x1)
  x2 = float(x2)
  y = int(y)
  data.append((x1,x2,y))

What is the purpose of readline here?这里 readline 的目的是什么? I have seen different examples but here seems that it delete the first line.我见过不同的例子,但这里似乎删除了第一行。

Python is reading the data serially, so if a line gets read once, python jumps to the next one. Python 正在串行读取数据,因此如果一行被读取一次,python 会跳转到下一行。 The r.readline() reads the first line, so in the loop it doesn't get read. r.readline() 读取第一行,因此在循环中它不会被读取。

That's precisely the point: to delete the first line.这正是重点:删除第一行。 If you notice, the file has the names of the columns as its first line ( x1,x2,y ), and the program wants to ignore that line.如果您注意到,该文件的第一行( x1,x2,y )包含列的名称,并且程序想要忽略该行。

Using readline() method before reading lines of file in loop is equals to:在循环读取文件行之前使用readline()方法等于:

for line in f.readlines()[1:]:     
    ...

for example that may be used to skip table header.例如,可用于跳过表 header。

In your file, when you will convert x1 variable to float type it raise ValueError because in first iteration x1 contain not digit sting type value "x1" .在您的文件中,当您将x1变量转换为浮点类型时,它会引发ValueError ,因为在第一次迭代中x1不包含数字字符串类型值"x1" And to avoid that error you use readline() to swich iterator to second line wich contain pure digits.为了避免该错误,您使用readline()将迭代器切换到包含纯数字的第二行。

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

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