简体   繁体   中英

extract last number in every row of CSV file

This is my second day of csv file handling, my CSV file:

-Rιalisι par James Wan--- Vos moments prιfιrιs ! (Spoilers inside) 1
-Source Code- News et Critique ! 2
ALED - A la carte 2
ALED - Bistrot 6

I would like to extract the number at the end and store it in another file like this:

hindex
1
2
2
6

The number could even be two digit..

If your content is in a file say tst.csv you can do something like

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

By definition the csv format is comma separated, therefore we use split(',') . infp is your input file handle (assuming the name of your data file is 'data.csv'), outfp for output:

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

EDIT: not withstanding the title of the question, apparently the file itself is in CSV format. CSV格式。 Therefore this solution would have to use split(' ') .

This is pseudo code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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