2

Edited because it seems as though I was too vague or didn't show enough research. My apologies (newbie here).

I am trying to read a csv file and assign each new line as a value to iterate through a script that writes to an API. There's no header data in my csv. I'll be adding a regex search and then using the data that follows the regex expression and assign it as a variable to iterate through my script if that makes sense.

CSV Contents:

Type1, test.com
Type2, name.exe
Type3, sample.com

Basic premise of what I want to do in Python:

Read from CSV Script runs with each line from the CSV as a variable (say Variable1). The script iterates until it is out of values in the csv list, then terminates. An example for the script syntax could be anything simple...

#!/usr/bin/python
import requests
import csv

reader = csv.reader(open('test.csv'))

for row in reader:
    echo line-item

until the script runs out of Variables to print, then terminates. Where I'm struggling is the syntax on how to take a line then assign it to a variable for the for loop.

I hope that makes sense!

1 Answer 1

5

You should take a look at the csv module.

Here's how you would use it:

import csv
file = csv.reader(open('file.csv'), delimiter=',')
for line in file:
    print(line)

This produces the following output:

['Type1', ' test.com']
['Type2', ' name.exe']
['Type3', ' sample.com']

It separates your lines into lists of strings at the occurrences of the delimiter you specify (a comma in this case).

If you want to read the file line by line (not as a CSV), you can just use:

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

Using the with statement makes sure that the file is closed after we are done reading its contents.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! That puts me on a much better path for getting this all to work. Have a good one.
@madwheel I've just seen your edit, one more detail to highlight: if you want to save the two different strings into two variables (and know that there are always two), you can do this in the first example instead of printing: (type, site) = line, where line == ['Type1', 'test.com']. This way type will be 'Type1' and site will become 'test.com', so you have the two values in two variables to work with.

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.