[英]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)
列表.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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.