0

my name is Rhein and I have just started to learn Python, and I'm having a lot of fun :D. I just finished a course on YouTube and I am currently working on a project of mine. Currently, I am trying to separate the columns into their own strings from a crime-data csv.

with open('C:/Users/aferdous/python-works/data-set/crime-data/crime_data-windows-1000.csv') as crime_data:
for crime in crime_data:
    id = crime_data.readline(8) #<- prints the first x char of each line
    print(id)
    case_number = crime_data.readline(8) #<- prints the first x char of each line
    print(case_number)
    date = crime_data.readline(22) #<- prints the first x char of each line
    print(date)
    block = crime_data.readline(25) #<- prints the first x char of each line
    print(block)

This was easy for the first two columns, since they all have the same amount of character lengths. But for 'block', the words in the columns have different lengths, so I do not know how to extract the right amount of characters from each word in each line. And there is a 1000 lines total. - Thanks

RHEIIIN
  • 3
  • 2
  • 2
    If you're trying to parse a CSV file, use [the `csv` module](https://docs.python.org/3/library/csv.html). It will make your life much easier. – abarnert Mar 29 '18 at 04:02
  • Meanwhile, `for crime in crime_data:` is already reading a line from your file each time through the loop—and then you ignore than and try to read another line character by character. Even if you get this to work, you're going to end up skipping every line. What you normally want to do is parse the `crime` line that you already have. But again, if you just use a `csv.reader`, you don't even have to do that; you just get each row broken down into a list of columns. – abarnert Mar 29 '18 at 04:04

1 Answers1

1

I assumen that your csv format is "value1, value2, value3" if that the case you can user a python function called split. Examples:

...
columns = crime_data.split(",")
print(columns[0]) #print column 1
print(columns[2]) #print column 2
...

But for read csv in python there a lot better options you can search in google a examples I found:

Dante
  • 295
  • 2
  • 12