[英]how to read several files into a python code and loop over them?
I am coding in python and have written a code which basically reads ina file takes some information from it does some calculations and then outputs the answers to a new file; 我正在用python编码,并编写了一个代码,该代码基本上读取一个文件,并从文件中获取一些信息,然后进行一些计算,然后将答案输出到一个新文件中。 I have now tried to generalise so that it loops over many files (as I have a catalogue of files I need to go through) by reading there file names in from a file in which they are listed.
现在,我尝试进行概括,以便通过从列出文件的文件中读取文件名来遍历许多文件(因为我需要浏览文件目录)。 However I get this error message IOError: [Errno socket error] [Errno -2] Name or service not known
但是,我收到此错误消息IOError:[Errno套接字错误] [Errno -2]名称或服务未知
I assume its because I am now trying to run my code for several files systematically so here is the bit of code in which I do it: 我以为是因为我现在正在尝试系统地为几个文件运行我的代码,因此这是我要做的一些代码:
f = open('//disk2/ps1/cech/CFHTLenS/cluster_catalogues/field_list')
fields = f.readlines()
f.close()
for W in fields:
file = open('//disk2/ps1/cech/CFHTLenS/cluster_catalogues/clusters_%s_info.cat' %W)
data = np.loadtxt(file)
file.close()
sig_cl = data[:,3].copy()
m200 = 10**(0.124 * sig_cl + 12.493)
np.savetxt('//disk2/ps1/bertbert/z_ref_%s.cat'%W,m200)
I'm not sure why you're getting a socket error from file handling routines, but the most obvious issue is that W
will have an end of line character at the end which is likely to cause problems. 我不确定为什么您会从文件处理例程中收到套接字错误,但是最明显的问题是
W
在结尾处会有一个行尾字符,这很可能会引起问题。
Try: 尝试:
W = W.strip()
as the first line of your for
loop. 作为
for
循环的第一行。
This will remove all leading and trailing spaces from W
before you add it to the name of the file to open. 在将其添加到要打开的文件名之前,这将从
W
删除所有前导和尾随空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.