我的目录中有100+文件,每个文件都有具有以下格式的1000+行:
name,sex,number前任:
xyz,M,234我需要得到这些文件的数字字段之和,只有在第2行出现一个特定的名称,而性别是'F‘的情况下。但是,在检查了条件之后,我的代码给出了目录中所有文件的数字字段之和。这是我的密码:
total = []
for filename in os.listdir(direc):
result = 0
if filename.endswith('.txt'):
file = open(direc + '/' + filename, 'r')
for i, line in enumerate(file, 1):
line = line.strip()
name, sex, count = line.split(',')
if 'xyz' == name and sex == 'F' and i == 2:
for line in file:
line = line.strip()
name, sex, count = line.split(',')
if sex == 'F':
result += int(count)
total.append(result)我的密码怎么了。我只需要我的第三栏中关于性爱= 'F‘的那些文件
'xyz' == name and sex == 'F' and i == 2发布于 2015-04-10 03:49:56
首先,您需要对同一个文件进行两次迭代,这肯定会使您的结果一团糟。
for i, line in enumerate(file, 1):和
for line in file:这里的部分问题是,文件对象不是内存中的列表--它是一个迭代器,一旦你看了一行,它就消失了。只要用一个列表把所有的行拉到内存中-- lines = list(file),检查第二行是否符合您的条件-- 'xyz', 'F' == lines[1].split(',')[:2] --然后对整个列表进行操作,如果是真的。
对于一个文件:
with open(filename) as f:
lines = list(f)
if 'xyz', 'F' == lines[1].split(',')[:2]:
result = 0
for line in lines:
name, sex, count = line.strip().split(',')
if sex == "F":
result += int(count)https://stackoverflow.com/questions/29552837
复制相似问题