我在两个目录中有数据,我正在使用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)
我哪里犯了错误??
如果我正确理解您的问题,您似乎想从path_to_files
和path_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')