Py学习  »  Python

如何在python中以相同的顺序从两个文件夹中读取文件

David • 1 年前 • 797 次点击  

我有两个文件名相同的文件夹,但当我试图从python中的文件夹中读取所有文本文件时,它的读取顺序不同。但我需要以相同的顺序从两个文件夹中读取文件,因为它们是对应的。我使用以下代码读取了文件夹中的所有文本文件。

 dir_psnr=current_path+'\\'+dir_psnr+'\\'
os.chdir(dir_psnr) #change directory to downloads folder
files_path =[os.path.abspath(x) for x in os.listdir()]
fnames_psnr_tmp = [x for x in files_path if x.endswith(".txt")]

文件夹的地址如下:

F:\RD_data_from_twitch_system\RD_data_from_twitch_system\psnr
F:\RD_data_from_twitch_system\RD_data_from_twitch_system\bitrate

两个文件夹中文本文件的名称如下:

asmr_1.txt
asmr_2.txt
Counter_strike_1.txt
Counter_strike_2.txt
dota2_1.txt

问题出在哪里?以及如何以相同的顺序读取文件? 完整代码为:

def reading_file_to_array(dir_psnr,current_path):
    dir_psnr=current_path+'\\'+dir_psnr+'\\'
    os.chdir(dir_psnr) #change directory to downloads folder
    files_path =[os.path.abspath(x) for x in os.listdir()]
    fnames_psnr_tmp = [x for x in files_path if x.endswith(".txt")]
   .
   .
   .         

    return()
current_path='F:/RD_data_from_twitch_system/RD_data_from_twitch_system'
current_dir ='F:/RD_data_from_twitch_system/RD_data_from_twitch_system'
all_sub_dir_paths = glob(str(current_dir) + '/*/') 
all_sub_dir_names = [Path(sub_dir).name for sub_dir in all_sub_dir_paths] 
    for i in range(len(all_sub_dir_names)):
    if all_sub_dir_names[i]=='bitrate':
        bitrate_1080p,bitrate_720p,bitrate_480p,bitrate_360p,bitrate_160p=reading_file_to_array(all_sub_dir_names[i], current_path)

    else:
        psnr_1080p,psnr_720p,psnr_480p,psnr_360p,psnr_160p=reading_file_to_array(all_sub_dir_names[i], current_path)
    
             
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/159032
 
797 次点击  
文章 [ 2 ]  |  最新文章 1 年前