python – Split a string in a CSV file by delimiter

python – Split a string in a CSV file by delimiter

You can almost always minimize the pain by using specialized tools, such as the csv module and list comprehension:

import csv
with open(yourfile.csv) as infile:
    reader = csv.reader(infile) # Create a new reader
    next(reader) # Skip the first row
    months = [row[0].split(-)[0] for row in reader]

One answer to your question is to use fileHandle.readlines().

lines = fileHandle.readlines()
# print(lines)
# [Date,Profit/Lossesn, Jan-10,867884n, Feb-10,984655n, Mar-10,322013n,
#  Apr-10,-69417n, May-10,310503n, Jun-10,522857n, Jul-10,1033096n, Aug-10,604885n,
#  Sep-10,-216386n, Oct-10,477532n, Nov-10,893810n, Dec-10,-80353n]

for line in lines[1:]:
    # Starting from 2nd item in the list since you just want months
    months.append(line.split(-)[0])

python – Split a string in a CSV file by delimiter

Try this if you really want to do it the hard way:

months = []
for line in lines[1:]:
    months.append(line.split(-)[0])

lines[1:] will skip the first row and line.split(-)[0] will only pull out the month and append to your list months.

However, as suggested by AChampion, you should really look into the csv or pandas packages.

Leave a Reply

Your email address will not be published. Required fields are marked *