枚举 glob.glob 对象后未定义变量

Variable not defined after enumerating glob.glob object

我目前有这个代码:

os.listdir("V:/FM003")
results = pd.DataFrame([])
for counter, file in enumerate(glob.glob("F5331_FM003**")):
    namedf = pd.read_csv(file, header=[0], skiprows=[0,1,2,3,4,5,6],  
    index_col=[0], usecols= [0,1])
    results = results.append(namedf)
print(namedf)

它一直返回错误"name 'namedf' is not defined"。任何人都可以帮我如何正确地写吗?我有点难过。

您在 for 循环内定义了 "namedf" 并在 for 循环外打印它。 只需在同一范围内编写打印语句即可。

os.listdir("V:/FM003")
results = pd.DataFrame([])
for counter, file in enumerate(glob.glob("F5331_FM003**")):
    namedf = pd.read_csv(file, header=[0], skiprows=[0,1,2,3,4,5,6],  
    index_col=[0], usecols= [0,1])
    results = results.append(namedf)
    print(namedf)

实际上我认为你的问题是你的 glob 没有访问正确的文件夹。因此没有找到这样的文件。

假设您要查找目录 V:/FM003 中的文件,您可以考虑使用:

for counter, file in enumerate(glob.glob("V:/FM003/F5331_FM003**")):

根据 docs:

glob.glob(pathname, *, recursive=False)

Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification.

构建此类路径规范的可靠方法是使用 os.path.join:

import os

folder = r'V:/FM003'
files = r'F5331_FM003**'
paths = os.path.join(folder, files)

for counter, file in enumerate(paths):
    ....