如何在Python的循环中将加载的表分配给不同的变量?

时间:2018-06-05 16:17:19

标签: python

我正在尝试使用循环导入n表,为每个表提供不同的名称。

我可以编写代码来导入表格,但我不能为每个表格提供不同的名称:

  1. 查找文件的路径(csv)

    totalbaseURL=('path')
    
  2. 找到所有csv文件

    folders = os.listdir(totalbaseURL)
    

    即,folders变为["house","cars","food","pubs"]

  3. folders包含csv文件的名称

    for f in folders:        
        path=totalbaseURL+f
        table=pd.read_csv(path,delimiter=';')
    
  4. 我怎么能把,而不是" table"?我想使用folders中的名称:( housecarsfoodpubs)。

3 个答案:

答案 0 :(得分:2)

使用dict,

folders=["house","cars","food","pubs"]

di = {}

for f in folders:        
    path=totalbaseURL+f
    di[f]=pd.read_csv(path,delimiter=';')

答案 1 :(得分:0)

你可以用dict来实现它:

{"house": DataFrame1, "cars": DataFrame2, "food": DataFrame3, "pubs": DataFrame4}

输出:

The layer 'Points' does not exist in the map's style and cannot be queried for features.

答案 2 :(得分:0)

error[E0499]: cannot borrow `*environment` as mutable more than once at a time
  --> src/main.rs:24:21
   |
23 |     let a = DataRef(environment.create_data(1));
   |                     ----------- first mutable borrow occurs here
24 |     let b = DataRef(environment.create_data(2));
   |                     ^^^^^^^^^^^ second mutable borrow occurs here
25 |     (a, b)
26 | }
   | - first borrow ends here

这将创建全局变量import os for f in folders: path = os.path.join(totalbaseURL, f) globals()[f] = pd.read_csv(path, delimiter=';') housecarsfood。如果此代码位于函数内,请使用pubs代替locals()