numpy/file-roundtrip
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | warning | none, edit by hand | All versions |
Writing an array as text with np.savetxt and parsing it back is slow and loses the dtype and the shape. Use np.save and np.load, which were hundreds of times faster.
np.savetxt("cache.txt", data)data = np.loadtxt("cache.txt")np.save("cache.npy", data)data = np.load("cache.npy")What the rule reports
Section titled “What the rule reports”The rule reports np.loadtxt(f) and np.genfromtxt(f) in a file that also calls np.savetxt(f, ...), and np.fromfile(f) in a file that also calls x.tofile(f), with the same file argument. np.save and np.load keep the dtype and the shape.
The rule requires a matching writer and reader in the same source file. For binary files it looks for a shared filename or a plain name, so it leaves a reader using a file object stored on self alone.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so make the change by hand.
Change the writer and reader together. np.save adds .npy to a filename that lacks it. Raw tofile output stores neither a dtype nor byte order.
Diagnostic message
Section titled “Diagnostic message”This program writes $FILE as text with np.savetxt and parses it back with $NP.$LOAD. Write it with np.save and read it with np.load, which ran 27 to 880 times faster reading and 420 to 510 times faster writing 1,000,000 values, and keeps the dtype and shape.See all rules in the NumPy pack.