Read csv file in python and iterate each line item as a value in a script?

三世轮回 提交于 2021-02-10 07:58:07

问题


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:


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.



来源:https://stackoverflow.com/questions/49266463/read-csv-file-in-python-and-iterate-each-line-item-as-a-value-in-a-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!