【问题标题】:How can I modify this to read from right to left and extract the lines? Instead of reading left to right如何修改它以从右到左读取并提取行?而不是从左到右阅读
【发布时间】:2021-02-09 06:47:46
【问题描述】:

使用此脚本,我可以根据“,”的位置将行分隔为不同的文本文件。而不是从左到右阅读和选择“,”,我如何修改它使其从右到左阅读?在我的 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

【问题讨论】:

  • 你的意思是使用parts[-2]
  • 参见sequence types 文档中关于负指数的注释(3)

标签: python file python-requests extract strip


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    相关资源
    最近更新 更多