Combining readline () and loop without using next () in python

I am trying to read several text files in a folder in order to build a specific column (last column) of each of the files. For this, I used the following code:

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 the read_ydata function is defined as follows:

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 the error message: ValueError: mixing iterations and reading methods will lose data and if I replace it with next (), I get an error: StopIteration.

Plz advice on how to get rid of these errors or implement my logic.

+1
source share
1 answer

Use either next(), or loop, or use .readline(), but do not mix both.

, .readline() ( ).

next(filename) filename.readline(), .

next() .readline() , , , .

, .rsplit() :

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

.rpartition():

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

while; 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))
+3

Source: https://habr.com/ru/post/1548198/


All Articles