2

I have a .csv file I am trying to read, but I'm having trouble. Please forgive me as this is a very remedial question:

I'm trying to read a file line-by-line with the following:

with open('Book8.csv') as fp:
for line in fp:
    print line

If I do this I print the whole file. like so:

1,2,3

4,5,6

7,8,9

However I only want to print the middle line so I put

 with open('Book8.csv') as fp:
for line in fp:
    print line[1]

This gives me

� , , as my output.

I want the output to be 4,5,6. It seems the commas or the [1] character in each line is being treated as part of the line. I'm not sure how to fix this.

Eventually I'm going to want to do a regular expression on each of these lines to search for multiple substrings in each line.

For example:

Line 1: There is text I want in here that text is _:E28, _:K31 blah blah

Line 2: There is text I want in here that text is _:H27, _:K12 blah blah

Will it be possible to write a regex to create a list for each line containing only my text of interest?

For example: List 1=[":E28", ":K31"] List 2=["_:H27", "_K12"]

1

3 Answers 3

4

Store your lines in a list and print from there. readlines() returns a list of every line in your file for you.

with open('Book8.csv') as fp:
    line = fp.readlines()

print(line[1])
Sign up to request clarification or add additional context in comments.

Comments

3

You are iterating over the string at position 1 which is just ,

import csv
with open ('Book8.csv','r') as csv_file:
    reader =csv.reader(csv_file)
    next(reader) # skip first row
    for row in reader:
        print(row)

2 Comments

Okay so that gives :['4', '5', '6'] ['7', '8', '9'] . What if I want to print just [7,8,9]? How do I get that without next?
Wait I answered my own question: if '7' in row: print row Many thanks!
0

As mentioned that you only want the middle row to get printed so you can use a simple row counter to actually count the rows and to only print the middle row

row_count = 0
with open('Book8.csv') as fp:
for line in fp:
    if row_count == 1:
        print line
    row_count+=1

If there is a case where there are multiple rows and you want all the middle rows to be printed except for the first and last one you can modify the code further

row_count = 0
with open('Book8.csv') as fp:
for line in fp:
    if row_count!=0 and row_count!=total_number_of_lines-1:
        print line
    row_count+=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.