简体   繁体   English

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

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

with this script I am able to separate lines into different text files based on the position of ",".使用此脚本,我可以根据“,”的位置将行分成不同的文本文件。 Instead of reading and choosing the "," from left to right, how can I modify it so it reads from right to left?不是从左到右阅读和选择“,”,我该如何修改它使其从右到左阅读? In my list.txt example, I would like to extract "1" from the first line, "14" from the second line, and "3" from the third line.在我的 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列表.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)

OR simply use index from right starting with -1 and you need -2 as below:或者简单地从 -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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM