简体   繁体   English

结合readline()和for循环而不在python中使用next()

[英]Combining readline() and for loop without using next() in python

I am trying to read multiple text files in a folder to plot a specific column(last column) of each of the file. 我正在尝试读取文件夹中的多个文本文件以绘制每个文件的特定列(最后一列)。 I have used the following code to do that: 我使用以下代码来做到这一点:

file_library = os.listdir(path)
for book in file_library:
 file = os.path.join(path, book)
  if file.endswith(".txt"):
    f = open(file, "r")
        for line in f:
            reads = read_ydata(f)
                print reads
        f.close()

where read_ydata function is defined as follows: 其中read_ydata函数定义如下:

y_values = []
line = filename.readline()
while line != '':
 y_val = line[line.rfind(' ') + 1:]
 y_values.append(float(y_val))
 line = filename.readline()
return y_values

Now when i run this i get an error: ValueError: Mixing iteration and read methods would lose data and if i replace it with next() i get the error: StopIteration. 现在,当我运行这个时,我得到一个错误:ValueError:混合迭代和读取方法将丢失数据,如果我用next()替换它我得到错误:StopIteration。

Plz advice as to how to get rid of these errors or to implement my logic.. 关于如何摆脱这些错误或实现我的逻辑的Plz建议..

Use either next() and looping, or use .readline() , but don't mix both. 使用 next()和循环, 使用.readline()但不要混用两种。

Using the file object as an iterable creates an internal buffer that would create confusion for what position the next .readline() will read from (which does not use a buffer). 将文件对象用作iterable会创建一个内部缓冲区,这会对下一个.readline()将从哪个位置读取(不使用缓冲区)造成混淆。

Just use next(filename) instead of filename.readline() and you are good. 只需使用next(filename)而不是filename.readline()可以了。

Both next() and .readline() return the line with the newline included, make sure you strip the line of whitespace before you test for the empty string. 两者next().readline()返回符合包括换行符,请确保你带空格的行,你测试空字符串之前。

Note that you can use .rsplit() to split off a value from the end of a line: 请注意,您可以使用.rsplit()从行尾分割出一个值:

y_val = line.rsplit(None, 1)[-1]

or use .rpartition() : 或使用.rpartition()

y_val = line.rpartition(' ')[-1]

Your function does not need to use a while loop; 你的函数不需要使用while循环; you could also just use a for loop and break when the line is empty: 你也可以只使用for循环并在行为空时中断:

y_values = []
for line in filename:
    if not line.strip():
        return y_values
    y_val = line.rsplit(None, 1)[-1]
    y_values.append(float(y_val))

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

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