在python中读取csv文件,并将每个订单项作为脚本中的值进行迭代? [英] Read csv file in python and iterate each line item as a value in a script?

查看:32
本文介绍了在python中读取csv文件,并将每个订单项作为脚本中的值进行迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行编辑,是因为我似乎太模糊或研究不足.我很抱歉(这里是新手).

我正在尝试读取一个csv文件,并将每个新行分配为一个值,以通过写入API的脚本进行迭代.我的csv中没有标题数据.我将添加一个正则表达式搜索,然后使用该正则表达式后的数据,并将其分配为变量,以便在我的脚本中进行迭代.

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内容:

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

我想在Python中做什么的基本前提:

Basic premise of what I want to do in Python:

从CSV读取脚本以CSV中的每一行作为变量运行(比如说Variable1).该脚本将进行迭代,直到其超出csv列表中的值,然后终止.脚本语法的示例可能很简单...

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

直到脚本用完变量"以进行打印,然后终止.我苦苦挣扎的是语法,该语法涉及如何取一行,然后将其分配给for循环的变量.

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.

我希望这是有道理的!

推荐答案

您应该看看这是您将如何使用它:

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

这将产生以下输出:

['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).

如果要逐行读取文件(而不是CSV),则可以使用:

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)

使用with语句可确保在我们阅读完文件的内容后将其关闭.

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

这篇关于在python中读取csv文件,并将每个订单项作为脚本中的值进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆