使用np.genfromtxt读取txt文件遇IOError:文件未找到求助
IOError with np.genfromtxt() and Missing File Hey there! I spot the issue immediately—you've defined your data directory DATADIR = "wave_data/", but you're not actually using it when calling np.genfromtxt()! That's why Python is searching for signal_1.txt in your current working directory instead of the wave_data folder where your files are stored.
Here's how to fix it:
The most reliable way (works across Windows, macOS, and Linux without path separator issues) is to use os.path.join() to combine your directory path and filename safely:
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import os from sklearn.preprocessing import StandardScaler, MinMaxScaler DATADIR = "wave_data/" # Combine directory path and filename properly data = np.genfromtxt(os.path.join(DATADIR, 'signal_1.txt'), delimiter=',')
If you prefer, you could also switch your working directory to wave_data first, though this is less flexible if you need to access files from other directories later:
os.chdir(DATADIR) data = np.genfromtxt('signal_1.txt', delimiter=',')
Quick sanity check:
If you're still uncertain about the file location, print your current working directory to confirm wave_data is located there:
print(os.getcwd())
Your original error for reference:
IOError Traceback (most recent call last)
in ()
----> 1 np.genfromtxt('signal_1.txt',delimiter=',')
/usr/lib/python2.7/dist-packages/numpy/lib/npyio.pyc in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows)
1547 if isinstance(fname, basestring):
1548 if sys.version_info[0] == 2:
-> 1549 fhd = iter(np.lib._datasource.open(fname, 'rbU'))
1550 else:
1551 fhd = iter(np.lib._datasource.open(fname, 'rb'))
/usr/lib/python2.7/dist-packages/numpy/lib/_datasource.pyc in open(path, mode, destpath)
149
150 ds = DataSource(destpath)
--> 151 return ds.open(path, mode)
152
153
/usr/lib/python2.7/dist-packages/numpy/lib/_datasource.pyc in open(self, path, mode)
499 return _file_openers[ext](found, mode=mode)
500 else:
--> 501 raise IOError("%s not found." % path)
502
503 IOError: signal_1.txt not found.
内容的提问来源于stack exchange,提问作者Blueberry

