我正在尝试使用以下代码导入CSV:
import csv
import sys
def load_csv(filename):
# Open file for reading
file = open(filename, 'r')
# Read in file
return csv.reader(file, delimiter=',', quotechar='\n')
def main(argv):
csv_file = load_csv("myfile.csv")
for item in csv_file:
print(item)
if __name__ == "__main__":
main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)
这是我的csv文件的示例:
foo,bar,test,1,2
this,wont,work,because,?
Run Code Online (Sandbox Code Playgroud)
而错误:
Traceback (most recent call last):
File "test.py", line 22, in <module>
main(sys.argv[1:])
File "test.py", line 18, in main
for item in csv_file:
File "/usr/lib/python3.2/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte …Run Code Online (Sandbox Code Playgroud) 可能重复:
Python中的转置/解压缩功能
我有一个序列列表,每个序列有两个项目.我想把它变成两个列表.
catalog = [('abc', '123'), ('foo', '456'), ('bar', '789'), ('test', '1337')]
Run Code Online (Sandbox Code Playgroud)
现在我只是这样做:
names = []
vals = []
for product in catalog:
names.append(product[0])
vals.append(product[1])
print (names)
print (vals)
Run Code Online (Sandbox Code Playgroud)
哪个输出两个列表,并且工作得很好:
['abc', 'foo', 'bar', 'test']
['123', '456', '789', '1337']
Run Code Online (Sandbox Code Playgroud)
有更整洁,更'pythonic'的方式吗?或者我应该坚持我拥有的东西?对编程风格的任何更正或反馈都是受欢迎的,我是新手,并试图学习最佳实践.