我是python的新手,现在需要使用“ with ... open ... as”将给定的csv文件导入pycharm,这是csv文件,请在此处输入图像描述
我想要的输出就像[[0,1),(0,6),(1,7),...]
请有人建议如何写作?
尝试这个:
from csv import reader
dataset = [] # Initialize an empty array so we can append elements into it.
with open('import-csv-as-coordinates-to-python.csv', newline='') as csvfile: # Open the csv file for reading.
csvreader = reader(csvfile, delimiter=',') # Initialize the csv reader from the file.
for rowid, row in enumerate(csvreader): # Go through every row in the list.
if rowid == 0: # This row contains the fields to the data, we can ignore it.
continue # Continue onto the next row.
dataset.append((row[1], row[2],)) # Add a tuple consisting of x, y to the list dataset.
print(dataset) # Output the dataset to make sure it worked.
您可以在此处找到csv模块的文档](https://docs.python.org/3/library/csv.html)。这是一个官方的内置模块。
如果愿意,还可以通过调用文件中的line.split(',')
每个line
文件来自己解析csv .readlines()
,就像这样。
dataset = []
with open('import-csv-as-coordinates-to-python.csv', newline='') as csvfile:
for rowid, row in enumerate(csvfile.readlines()):
row = row.strip().split(',')
if rowid == 0:
continue
dataset.append((row[1], row[2],))
print(dataset)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句