我正在尝试从以下格式的大型 CSV 文件中提取数据,假设“x”是文本或整数形式的数据。每个分组都有一个唯一的 id,但每个分组或颜色的行数并不总是相同。数据用逗号与颜色分开。
id, x
red, x
green, x
blue, x
black, x
id, x
yellow, x
green,
blue, x
black, x
id, x
red, x
green, x
blue, x
black, x
id, x
red, x
green, x
blue, x
id, x
red, x
green, x
blue, x
black, x
我想以列格式重新排列数据。ID 应该是第一列,任何数据都用逗号分隔。我的目标是让它读取行中的第一个单词并将其放在适当的列中。
line 0 - ID - red - green - blue - yellow - black
line 1 - x, x, x, , x,
line 2 - , x, x, x, x,
line 3 - x, x, x, , x,
line 4 - x, x, x, , ,
line 5 - x, x, x, , x,
这就是我正在尝试的...
readfile = open("db-short.txt", "r")
datafilelines = readfile.readlines()
writefile = open("sample.csv", "w")
temp_data_list = ["",]*7
td_index = 0
for line_with_return in datafilelines:
line = line_with_return.replace('\n','')
if not line == '':
if not (line.startswith("ID") or
line.startswith("RED") or
line.startswith("GREEN") or
line.startswith("BLUE") or
line.startswith("YELLOW") or
line.startswith("BLACK") ):
temp_data_list[td_index] = line
td_index += 1
temp_data_list[6] = line
if (line.startswith("BLACK") or line.startswith("BLACK")):
temp_data_list[5] = line
if (line.startswith("YELLOW") or line.startswith("YELLOW")):
temp_data_list[4] = line
if (line.startswith("BLUE") or line.startswith("BLUE")):
temp_data_list[3] = line
if (line.startswith("GREEN") or line.startswith("GREEN")):
temp_data_list[2] = line
if (line.startswith("RED") or line.startswith("RED")):
temp_data_list[1] = line
if (line.startswith("ID") or line.find("ID") > 0):
temp_data_list[0] = line
if line == '':
temp_data_str = ""
for temp_data in temp_data_list:
temp_data_str += temp_data + ","
temp_data_str = temp_data_str[0:-1] + "\n"
writefile.write(temp_data_str)
temp_data_list = ["",]*7
td_index = 0
if temp_data_list[0]:
temp_data_str = ""
for temp_data in temp_data_list:
temp_data_str += temp_data + ","
temp_data_str = temp_data_str[0:-1] + "\n"
writefile.write(temp_data_str)
readfile.close()
writefile.close()