Python继续打印for循环的第一个索引

时间:2018-09-12 13:38:36

标签: python-2.7 file for-loop operating-system

我在两个目录中都有数据,我正在使用for loop从两个文件夹中读取文件。

path_to_files = '/home/Desktop/computed_2d/'
path_to_files1 = '/home/Desktop/computed_1d/'

for filen in [x for x in os.listdir(path_to_files) if '.ares' in x]:
    df = pd.read_table(path_to_files+filen, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')

    for filen1 in [x for x in os.listdir(path_to_files1) if '.ares' in x]:
        df1 = pd.read_table(path_to_files1+filen1, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')

        print(filen,filen1)

现在发生的事情就像是尝试打印文件名然后一直打印名称一样。因此,它基本上是从第一个循环中提取第一个迭代,然后在第二个循环的所有迭代中将其打印出来。我不知道为什么会这样。

但是我想做的是,我要打印第一个loop的第一次迭代和第二个for loop的第一次迭代

因为两个文件夹中的文件名都相同。所以当我打印时,所需的结果应该像这样:

(txt_1.txt,txt_1.txt)
(txt_2.txt,txt_2.txt)
(txt_3.txt,txt_3.txt)
(txt_4.txt,txt_4.txt)

我在哪里犯错了?

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则您似乎希望打印path_to_filespath_to_files1中的文件对。由于您要嵌套for loop,因此对于嵌套for loop的每次迭代,filen都不会改变。

我想你可能想要更多这样的东西:

path_to_files = '/home/Desktop/computed_2d/'
path_to_files1 = '/home/Desktop/computed_1d/'

filelistn = [x for x in os.listdir(path_to_files) if '.ares' in x]
filelist1 = [x for x in os.listdir(path_to_files1) if '.ares' in x]

for filen, filen1 in zip(filelistn, filelist1):
    df = pd.read_table(path_to_files+filen, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')
    df1 = pd.read_table(path_to_files1+filen1, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')

    print(filen,filen1)

对于以下示例输入:

filelistn = ['a.ar', 'b.ar']
filelist1 = ['c.ar', 'd.ar']

我得到以下输出:

('a.ar', 'c.ar')
('b.ar', 'd.ar')