首页 > 解决方案 > CSV 迭代/循环

问题描述

我正在尝试遍历 CSV 行的所有单元格(名称、屏幕名称和图像 url)。出现了不同的错误,我尝试使用 pandas,但仍然无法完成工作。我的 CSV 看起来像这样:

screen_name,name,image_url_https
Jan,Jan,https://twimg.com/sticky/default_profile_images/default_profile_normal.png
greg,Gregory Kara,https://twimg.com/profile_images/60709109/Ferran_Adria_normal.jpg
hillheadshow,Hillhead 2020,https://twimg.com/profile_images/1192061150915178496/cF6jOCRV_normal.jpg
hectaresbe,Hectaresbe,https://twimg.com/profile_images/1190957150996226048/lJnRnFwi_normal.jpg
Sdzz,Sanne,https://twimg.com/profile_images/1159005129879801856/8p6KC1ei_normal.jpg

我需要更改的部分代码是:

import json
import time,os
import pandas as pd

screen_name = 'mylist'

file = pd.read_csv("news2.csv", header=0)

col = file.head(0)

columns = list(col)

fp=codecs.open(screen_name+'.csv','w',encoding="utf-8")
i=0
while True:
    try:
        i+=1
        print (i)
        name=['name']
        uname=['screen_name']
        urlimage=['image_url_https']

@Snake_py 代码的值没问题,接下来我正在做一个请求:

myrequest='https://requesturl.com/'+uname
#print(myrequest)
resp=requests.get(myrequest)

我收到以下错误:

raise InvalidSchema("No connection adapters were found for '%s'" % url)requests.exceptions.InvalidSchema: No connection adapters were found for '0    https://requesturl.com/Jan

名称:名称,dtype:对象'

捕获超时错误。

标签: loopscsv

解决方案


使用 Python 遍历 csv 的最简单方法是:

name = []
uname = []
urlimage =[]

open with ('url', 'r') as file:
  for row in file:
     row = row.strip().split(";")
     name.append(row[0])
     uname.append(row[1])
     urlimage.append(row[2])

print(name)
print(uname)
print(urlimage)    

首先,我创建了三个空数组。然后我打开文件并遍历文件中的每一行。行将作为数组返回。因此,您可以运行正常的索引命令 [] 来获取数组的所需部分,以将其附加到空列表中。对于上面的方法,您可能会遇到编码问题,因此我会推荐方法 2,尽管您实际上并没有遍历行。

或者你可以这样做:

import pandas as pd

file = pd.read_csv("news2.csv", header=0)

name = file['name']
uname = file['uname']
urlimage = file['urlimage']

对于第二种方法,您需要确保您的标题拼写正确


推荐阅读