Python文件嵌套循环 [英] Python nested loop from files

查看:53
本文介绍了Python文件嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

inputActionFile = '../action.txt'
inputDaerahFile = '../daerah.txt'
inputStuffFile = '../stuff.txt'
inputTermsFile = '../terms.txt'

outputFile = 'hasil.out'

inputAction = open(inputActionFile, 'r')
inputDaerah = open(inputDaerahFile, 'r')
inputStuff = open(inputStuffFile, 'r')
inputTerms = open(inputTermsFile, 'r')

output = open(outputFile, 'w')

for actionLine in inputAction:
 for daerahLine in inputDaerah:
  for stuffLine in inputStuff:
   for termsLine in inputTerms:
    keyword = actionLine.strip() + ' ' + daerahLine.strip() + ' ' + stuffLine.strip() + ' ' + termsLine
    output.write(keyword)

inputAction.close()
inputDaerah.close()
inputStuff.close()
inputTerms.close()
output.close()

我希望结果将遍历所有这些文件,并将它们一一嵌套到输出文件中.但是,它只是迭代第四个循环.我在BaSH中做了类似的事情,想看看如何在Python中做到这一点.BaSH代码如下:

I expected the results to be looping through all these files and nesting them one by one to the output file. However, it just iterates the fourth loop. I was doing a similar thing in BaSH and want to see how to do it in Python. The BaSH code is as follows:

#!/bin/sh
input1=$1
input2=$2
input3=$3
input4=$4
output=$5

echo "###START###" > $output
#old_IFS=$IFS
IFS='
'  # new field separator, EOL

for line1 in `cat $input1`;
do
 for line2 in `cat $input2`;
 do
  for line3 in `cat $input3`;
  do
   for line4 in `cat $input4`;
   do
    echo $line1 $line2 $line3 $line4 >> $output;
   done
  done
 done
done

unset IFS;
#IFS=$old_IFS

推荐答案

每个循环只会遍历文件一次.成功遍历

Each loop will just go through the file once. After having sucessfully looped through

for termsLine in inputTerms:

每次到达inputTerms文件的末尾时,它每次都将跳过此循环.

Once, every time it gets there, it will skip this loop, as you have reached the end of the inputTerms file.

您需要在每个循环中重新打开每个文件(或至少在它们上查找(0)),或者将文件读入内存中的列表中.

You need to either reopen each file in each loop, (or at least seek(0) on them), or read in the files into a list in memory.

所以,要么:

inputAction = open(inputActionFile, 'r').readlines()
inputDaerah = open(inputDaerahFile, 'r').readlines()
inputStuff = open(inputStuffFile, 'r').readlines()
inputTerms = open(inputTermsFile, 'r').readlines()

或者:

for actionLine in open(inputActionFile, 'r'):
 for daerahLine in open(inputDaerahFile, 'r'):
  for stuffLine in open(inputStuffFile, 'r'):
   for termsLine in open(inputTermsFile, 'r'):
       etc....

这篇关于Python文件嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆