在 Python 中将 CSV 文件的行读入字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16268174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading rows of CSV file into string in Python
提问by user2330104
So I have a string of id's in numbers saved as CSVs
所以我有一串 id 的数字保存为 CSV
i.e.) http://i.imgur.com/atCJJCx.png
即)http://i.imgur.com/atCJJCx.png
And I want is to convert each rows on this csv file to be a string/list in python
我想要的是将此 csv 文件中的每一行转换为 python 中的字符串/列表
mylist=[411211, 1234404, 5711427, 13600442, 13600641, 13601660, 13619537, 15302899 ...]
Then each numbers on this string will go through an API request and then spit out Names
然后这个字符串上的每个数字都会经过一个API请求然后吐出Names
Then I want to be able to store these names in csv again.
然后我希望能够再次将这些名称存储在 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...
我知道通过 API 将数字转换为名称的代码有效,因为我尝试在 python 中手动输入数字作为列表,并且能够在 python 中打印出名称。但是我在使用 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
But this prints me the results I want! I just need to figure out how to store into a csv...
但这会打印出我想要的结果!我只需要弄清楚如何存储到 csv 中...
采纳答案by Stephane Rolland
if you go to csv in docs python, the example is:
如果您在 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.
我认为这是一个伟大而简单的例子。

