我正尝试通过以下方式遍历文件目录:
path = r'C:\my\path'
for filename in os.listdir(path):
nodes_arr = np.genfromtxt(filename, delimiter=',')
我得到一个错误:
IOError("%s not found." % path)
OSError: 10028057_nodes not found.
当我尝试通过以下方式打印文件时:
path = r'C:\my\path'
for filename in os.listdir(path):
print(filename)
我得到一个列表,它包含目录中的所有文件,第一个是“ 10028057_nodes”,它提供了错误信息...
答案 0 :(得分:2)
os.listdir
仅返回文件名。 Python IO函数,无论是直接(open
...)还是通过numpy
调用,实际上并不知道这些名称位于path
中。除非您的路径是当前目录(Python会假设该路径),否则它将失败-因为该文件名在当前目录中不存在。
您需要的是连接文件名的路径,因此:
nodes_arr = np.genfromtxt(os.path.join(path, filename), delimiter=',')
答案 1 :(得分:0)
尝试通过绝对路径,如下所示:
nodes_arr = np.genfromtxt(os.path.join(path,filename), delimiter=',')
如果您希望代码正常工作,则python代码文件必须与其他文件位于同一文件夹中。
答案 2 :(得分:0)
os.listdir 为您提供文件名,您仍然需要加入路径以获取其实际路径。
path = r'C:\my\path'
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
nodes_arr = np.genfromtxt(file_path, delimiter=',')