在 python 中映射 csv
我正在尝试在 python 中的 csv 文件上使用“map”。
然而,map(lambda x: x, reseller_csv)
行什么也没给出。
我尝试迭代 csv 对象,它工作正常并且可以打印行。
这是代码。
# imports
import csv
# Opens files
ifile = open('C:\Users\josh.SCL\Desktop\Records.csv', 'r')
ofile = open('C:\Users\josh.SCL\Desktop\RecordsNew.csv', 'w')
resellers_file = open('C:\Users\josh.SCL\Desktop\Reseller.csv', 'r')
# Setup CSV objects
csvfile = csv.DictReader(ifile, delimiter=',')
reseller_csv = csv.DictReader(resellers_file, delimiter=',')
# Get names only in resellers
resellers = map(lambda x: x.get('Reseller'), reseller_csv)
I'm trying to use "map" on a csv file in python.
However, the line map(lambda x: x, reseller_csv)
gives nothing.
I've tried iterating over the csv object, and it works fine and can print the rows.
Here's the code.
# imports
import csv
# Opens files
ifile = open('C:\Users\josh.SCL\Desktop\Records.csv', 'r')
ofile = open('C:\Users\josh.SCL\Desktop\RecordsNew.csv', 'w')
resellers_file = open('C:\Users\josh.SCL\Desktop\Reseller.csv', 'r')
# Setup CSV objects
csvfile = csv.DictReader(ifile, delimiter=',')
reseller_csv = csv.DictReader(resellers_file, delimiter=',')
# Get names only in resellers
resellers = map(lambda x: x.get('Reseller'), reseller_csv)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
csv.DictReader 是一个一次性使用的小工具。您可能已经运行了第二次。
当我们在这里时:
(1) [Python 2.x] 始终以 BINARY 模式打开 csv 文件。
[Python 3.x] 始终以文本模式(默认)打开 csv 文件,并使用
newline=''
(2) 如果您坚持在 Windows 中硬编码文件路径,请使用 r"... .”而不是“...”,或使用正斜杠 - 否则
\n
和\t
将被解释为控制字符。A csv.DictReader is a use-once gadget. You probably ran it a second time.
While we're here:
(1) [Python 2.x] Always open csv files in BINARY mode.
[Python 3.x] Always open csv files in text mode (the default), and use
newline=''
(2) If you insist on hardcoding file paths in Windows, use r"...." instead of "...", or use forward slashes -- otherwise
\n
and\t
will be interpreted as control characters.以下内容对我有用:
您确定从
DictReader
中获取了任何数据吗?在此之前您是否读取过任何数据,也许会让读者筋疲力尽?The following works for me:
Are you sure you get any data at all from your
DictReader
? Do you read any data from it prior to that, exhausting the reader perhaps?首先针对您的具体问题:尝试检查是否确实存在名为“Reseller”的密钥,很可能它的大小写不同或有额外的空间。查看所有键的列表(假设未耗尽 DictReader):
否则
map()
应该可以正常工作。但我认为这样做更具可读性(而且更快!):First on your specific problem: try checking if there is actually a key named 'Reseller', chances are its there with different capitalization or extra space. See list of all the keys (assuming non-exhausted DictReader):
Otherwise the
map()
should work fine. But i'd argue it's more readable (and faster!) done like this: