在Python中将CSV文件的行读取为字符串 [英] Reading rows of CSV file into string in Python

查看:695
本文介绍了在Python中将CSV文件的行读取为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个ID字符串,其数字另存为CSV

So I have a string of id's in numbers saved as CSVs

ie) http://i.imgur.com/atCJJCx.png

我想将csv文件上的每一行转换为python中的字符串/列表

And I want is to convert each rows on this csv file to be a string/list in python

mylist=[411211, 1234404, 5711427, 13600442, 13600641, 13601660, 13619537, 15302899 ...]

然后,此字符串上的每个数字都会通过API请求,然后吐出名称

Then each numbers on this string will go through an API request and then spit out Names

然后,我希望能够再次将这些名称存储在csv中.

Then I want to be able to store these names in csv again.

我知道通过API将数字转换为名称的代码是可行的,因为我尝试手动将数字输入为python中的列表,并能够在python中打印出名称.但是我在使用csv时遇到了麻烦...

I know the code for converting numbers to names via API works because I tried to manually type in the numbers as lists in python and was able to print out names in python. But I'm having a trouble working with csv...

好吧,所以转换成列表以某种方式起作用了... 我还是不完全了解...(忘了说我是这门编程的新手...)

Okayyy so converting into list somehow worked... I still don't fully understand how... (forgot to mention I'm a novice to this whole programming thing...)

import urllib2
import json
import csv

with open('jfl42facebooknumberid.csv', 'rU') as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONE)

    for row in reader:
        myid='. '.join(row)
        try:
            myfile=urllib2.urlopen("http://graph.facebook.com/"+ myid +"?fields=name")
            myjson=json.loads(myfile.read())
            print myjson["name"]
        except:
            print myid

但这会打印出我想要的结果!我只需要弄清楚如何存储到csv ...

But this prints me the results I want! I just need to figure out how to store into a csv...

推荐答案

如果您转到docs python中的csv ,示例为:

import csv
with open('eggs.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        print ', '.join(row)

我认为这是一个非常简单的例子.

I think it is a great and simple example.

这篇关于在Python中将CSV文件的行读取为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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