我正在将CSV文件中的项目加载到列表中。现在,我正在尝试在每个换行符上拆分列表,而我正在这样做。
这是我的代码。
mylist=[]
file = open('C:\\Users\\Excel\\Desktop\\test.csv')
for line in file:
mylist.append(line)
import pandas as pd
import pypyodbc
cnxn = pypyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server=server_name;'
'Database=db_name;'
'Trusted_Connection=yes;')
#print(cnxn)
for item in mylist:
#for line in mylist:
print(item)
sql_for_df = 'select * ' + item.split(',')
item_order = pd.read_sql(sql_for_df , cnxn)
order_details = pd.read_sql(sql_for_df , cnxn)
orders = pd.read_sql(sql_for_df , cnxn)
from functools import reduce
dfs = [item_order, order_details, orders]
df_final = reduce(lambda left,right: pd.merge(left,right,on='OrderID'), dfs)
此:
print(item)
给我这个:
ItemOrder
Order Details
Orders
但是,当我尝试将其连接时,如下所示:
sql_for_df = 'select * ' + item.split(',')
我遇到此错误。
TypeError: can only concatenate str (not "list") to str
几乎就像正确地拆分了列表一样,然后又从列表恢复为原始格式。我在这里做什么错了?
答案 0 :(得分:0)
再看一遍,我自己弄清楚了。感谢您的不赞成票!
这是最终可行的解决方案。
mylist=[]
file = open('C:\\Users\\Excel\\Desktop\\test.csv')
for line in file:
mylist.append(line)
import pandas as pd
import pypyodbc
cnxn = pypyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server=server_name;'
'Database=db_name;'
'Trusted_Connection=yes;')
for item in mylist:
#print(item)
sql_for_df = 'select * from ' + item
orders = pd.read_sql(sql_for_df , cnxn)
print(orders)
from functools import reduce
dfs = [item_order, order_details, orders]
df_final = reduce(lambda left,right: pd.merge(left,right,on='OrderID'), dfs)