首页 > 解决方案 > Python不断打印for循环的第一个索引

问题描述

我在两个目录中有数据,我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)

现在发生的事情就像尝试打印文件名然后它一直打印名称一样。所以,它基本上是从第一个循环中进行第一次迭代,然后用第二个循环的所有迭代打印它。我不明白为什么会这样。

但我想做的是,我想打印 firstloop的第一次迭代和 second 的第一次迭代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)

我在哪里犯错误??

标签: python-2.7filefor-loopoperating-system

解决方案


如果我正确理解您的问题,您似乎想从path_to_files和打印成对的文件path_to_files1。由于您正在嵌套 a for loop,因此对于嵌套的每次迭代for loopfilen都不会改变。

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

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')

推荐阅读