Home>

I want to load an external file line by line at any time with python.

More specifically

for i in range (0,10):
    for j in range (0,10):
        #I want to read one line here
It ’s like

. However, when I examined it,
Because it looks like a for-each statement, I could only find something that took out the line.
( eg here )
How can I write the above code?
(I would be happy if there is a function that can be read "one by one" separated by whitespace, such as java or c ++ ...)

Appendix

Thank you for teaching me.
I'm glad.
Executed the following code based on your answers

AttributeError: '_io.TextIOWrapper' object has no attribute 'readLine'


Error (it also appeared when trying next ()). What is the cause of this?

import h5py
import numpy as np
# matplotlibl.use ('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors as colors
f = open ("result.out", "r +")
X, Y = np.meshgrid (np.arange (-5, 5, 1), np.arange (-5, 5, 1))
Z = np.empty ((10, 10), float)
for i in range (0, 10):
    for j in range (0, 10):
        R, T, A = f.readLine (). Split ("")
        Z [j] [i] = A
fig = plt.figure ()
ax = fig.add_subplot (111)
im = ax.contourf (X, Y, Z, cmap = 'bwr')
fig.colorbar (im)
plt.savefig ("out.png");
plt.close ();
  • Answer # 1

      

    More specifically ...

    Use itertools.product and use zip at the same time.

    from itertools import product
    with open ('spam.txt') as fin:
        it = product (range (10), repeat = 2)
        for (x, y), line in zip (it, fin):
            line = line.strip ()
            print (x, y, line)

    Wandbox

    If you need a more complicated loop, use next to pull it out once.

    with open ('spam.txt') as fin:
        try:
            for x in range (10):
                for y in range (10):
                    line = next (fin) .strip ()
                    print (x, y, line)
        except StopIteration:
            pass

    Wandbox

    Addition:For files, readline is more natural.

      

    More specifically, I would be happy if there was a function that could read "one by one" separated by whitespace like java and c ++ ...

    You may want to prepare something like this.

    from itertools import chain
    def gen_next_token (fin):
        return chain.from_iterable (
            line.split () for line in map (str.strip, fin)
        )
    def gen_next_token (fin):
        for line in map (str.strip, fin):
            yield from line.split ()
    In response to additional questions
    AttributeError: '_io.TextIOWrapper' object has no attribute 'readLine'

    Typo.readLinereadline

      

    I get an error (when I tried next (), it came out)

    Note that

    next itself is a global function, not a method.

    Added

    Speaking only the code presented, I think it will be easier to write.

    with open ('result.out', mode = 'r +') as fin:
        Z = np.array (
            [int (line.split () [-1]) for line in fin], dtype = float
        ) .reshape (10, 10)

  • Answer # 2

    [Python] Read file contents (read, readline, readlines)

  • Answer # 3

    https: //www.tutorialspoint .com/python/file_next.htm

    You should use next ().