我如何修改它以从右到左阅读并提取行?而不是从左到右阅读

How can I modify this to read from right to left and extract the lines? Instead of reading left to right

使用此脚本,我可以根据“,”的位置将行分隔到不同的文本文件中。与其从左到右阅读和选择“,”,不如如何修改它以使其从右到左阅读?在我的 list.txt 示例中,我想从第一行提取“1”,从第二行提取“14”,从第三行提取“3”。

with open("list.txt", 'r') as file:
   for line in file:
      parts = line.strip().split(',')
      with open(f"{parts[2]}.txt", 'a+') as file2:
         file2.write(line)

list.txt

Honda,engine,1,yes
Honda,cooling+system,car,14,no
Honda,heat+&+air+conditioning,heat,car,3,no
with open("list.txt", 'r') as file, :
   for line in file:
      parts = line.strip().split(',')
      parts = parts[::-1]  # reverses the list
      with open(f"{parts[1]}.txt", 'a+') as file2: # number is the second element so index is 1
         file2.write(line)

或者只需使用从右开始的索引,从 -1 开始,您需要 -2,如下所示:

with open("list.txt", 'r') as file, :
   for line in file:
      parts = line.strip().split(',')
      with open(f"{parts[-2]}.txt", 'a+') as file2:
         file2.write(line)