提取CSV fi每行的最后一个数字

2024-09-29 01:34:38 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我处理csv文件的第二天 CSV文件:

-Rιalisιpar James Wan---Vos时刻prιfιRιs!(内部扰流板)1
-源代码-新闻和评论!2
点菜2
阿莱德-比斯特罗6

我想提取末尾的数字并将其存储在另一个类似这样的文件中:

hindex
1
2
2
6

这个数字甚至可以是两位数。。在


Tags: 文件csv源代码评论数字pr新闻par
3条回答

如果你的内容在一个文件中,说tst.csv你可以做如下的事情

>>> with open("tst.csv") as fin, open("tst.out","w" )as fout:
    for line in fin:
        fout.write(line.rpartition(" ")[-1])

这是伪代码:

 foreach line
     split the line words by space and get the last index. 

根据定义,csv格式是逗号分隔的,因此我们使用split(',')infp是输入文件句柄(假设数据文件的名称是'数据.csv'),outfp用于输出:

with open('data.csv') as infp, open('data.out', 'w') as outfp:
   for line in infp:
      outfp.write(line.split(',')[-1])

编辑:不管问题的标题是什么,显然文件本身不是CSV格式的。因此,这个解决方案必须使用split(' ')。在

相关问题 更多 >