我有一个在Cinema 4d项目中为我工作的代码。它能够读取4个不同的数据点,并将输出踢到主项目。目前,它正在读取csv文件的所有行,我想选择一行并仅从该行提取数据。
import c4d
import csv
def main():
path = Spreadsheet #Spreadsheet is an input filename path
with open(path, 'rb') as csv_file:
readed = csv.DictReader(csv_file,delimiter=',')
for i, row in enumerate(readed):
try:
Xcord = float(row["hc_x"])
Ycord = float(row["hc_y"])
Langle = float(row["launch_angle"])
Lspeed = float(row["launch_speed"])
except:
print "Error while reading - {}".format(row)
continue
global Output1
global Output2
global Output3
global Output4
Output1 = Xcord
Output2 = Ycord
Output3 = Langle
Output4 = Lspeed
这是我试图编码的第一件事。所以谢谢。
。DictReader要求您使用newline="为了使它能够正确解析文件。
with open(path, 'rb', newline="") as csv_file:
readed = csv.DictReader(csv_file,delimiter=',')
您也没有任何条件停止读取文件。
row_to_stop = 5
for i, row in enumerate(readed):
if i == row_to_stop:
Xcord = float(row["hc_x"])
Ycord = float(row["hc_y"])
Langle = float(row["launch_angle"])
Lspeed = float(row["launch_speed"])
break
如果你只关心一行,不要查找并输入强制转换值,直到你到达你关心的行。
我想选择一行并只从该行提取数据
下面的代码将返回特定的行(按索引)。你必须拆分它并获取数据。
def get_interesting_line(file_name: str, idx: int):
cnt = 0
with open(file_name) as f:
while cnt != idx:
f.readline()
cnt += 1
return f.readline().strip()
# usage example below
print(get_interesting_line('data.txt',7))