Skip to main content
 首页 » 编程设计

python之使用全局字典创建变量

2025年05月04日18grandyang

我需要根据文件夹中的文件列表创建未知数量的 python 变量。

我发现我可以使用全局字典来创建和初始化这些变量:

# libraries import 
import os.path 
import glob 
import numpy as np 
 
# list of all the text files in the folder 
list = glob.glob("*.txt") 
 
# creation of the variables based on the name of each file 
for file in list: 
    shortname = os.path.splitext(file)[0] 
    globals()[shortname] = np.loadtxt(file)  

但是,我想知道在 python 中访问全局字典进行变量赋值是否是一个好习惯(当我们事先不知道变量的数量和名称时),或者是否有更好的替代方法。

请您参考如下方法:

你应该为此使用专用字典:

files = {f: np.loadtxt(f) for f in glob.glob("*.txt")} 

通常,您不应混合使用数据和变量或属性名称。如果存在同名文件,您的代码可以隐藏任何 Python 内置文件。