【发布时间】:2021-10-13 20:19:58
【问题描述】:
我的程序应该从 csv 文件中获取数据并将每一行转换为按列组织的元组。但是,当我运行它时,它会将元组作为每个字符作为元组元素返回,而不是字符串元组。例如,如果一行由这些列组织:'Order Date'、'Order Date'、'Group'、'Description',则应将它们作为元组返回,其中每个标题作为元组的元素(4元素)。如何修复它以正确返回元组?
代码如下:
import csv
def list_to_tuple(input_file):
csvfile = open(input_file) #open the input file
input_content = csvfile.readlines() #get the content of the input file and store as a double array
csvfile.close() # dont need the file anymore i can close it
final_list = []
for lines in range(len(input_content)):
input_content[lines] = input_content[lines].split(',')
for lines in range(len(input_content)):
for words in range(len(input_content[lines])):
input_content[lines][words] = input_content[lines][words].strip()
input_content[lines][words] = input_content[lines][words].lower()
for i in range(len(input_content)):
Order_Date = input_content[i][0]
Order_ID = input_content[i][1]
Group = input_content[i][2]
Item_Category = input_content[i][3]
Description = input_content[i][4]
Seller = input_content[i][-2]
Item_Total = input_content[i][-1]
item = ('{},{},{},{},{},{},{}'.format(Order_Date, Order_ID, Group, Item_Category, Description, Seller, Item_Total))
final_list.append(tuple(item))
return final_list
input_file = 'orders.csv'
final_output = list_to_tuple(input_file)
print(final_output)
【问题讨论】:
-
不要发布文字图片。发布文本。特别是,不要发布某些电子表格软件的屏幕截图...发布 csv 本身。
-
您尝试过使用
inputcontent[lines].split(',')并遍历返回的列表,还是使用CSV module? -
另外,请以正确格式发布您的代码
-
无论如何,
item = ('{},{},{},{},{},{},{}'.format(Order_Date, Order_ID, Group, Item_Category, Description, Seller, Item_Total))创建了一个str。然后你做final_list.append(tuple(item))。当您拨打tuple("hello,I,am,a,string")时会发生什么? -
抱歉,我在之前的帖子中被告知要发布 csv 文件内容的图像。谢谢您的意见。我看到它作为单独的字母返回。那么这是否是正确的更改: item = list(Order_Date,Order_ID,Group,Item_Category,Description,Seller,Item_Total) final_list.append(tuple(item))