python - 为具有相同扩展名的多个文件运行脚本。获取 'UnboundLocalError'

标签 python glob

我正在尝试编写一个脚本来从扩展名为“.tp6”的目录中的多个文件中提取数据 - 最终我会将它们写入带有关联文件名的 csv 中,但我现在不关注这个。

下面的代码适用于大约 50 个文件,然后突然收到一个“UnboundLocalError”,内容如下:

Traceback (most recent call last):

File "finder5.py", line 22, in module

uncovext(file)

文件“finder5.py”,第 17 行,非凸面

print ('%.3f' % outfloat)

UnboundLocalError:赋值前引用了局部变量“outfloat”。

这是代码:

import Tkinter as tk
import tkFileDialog
import os
import glob

#defines the working directory
root = tk.Tk()
root.withdraw()
dir_path = tkFileDialog.askdirectory()
os.chdir(dir_path)

def uncovext(file1):
    for line in open(file1, 'r'):
        if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
            out = line[36:47]
            outfloat = (float(out) * 10000)
    print('%.3f' % outfloat)
    print(file)

#for each file with ext ".tp6"
for file in glob.glob("*.tp6"):
    uncovext(file)

有什么想法吗?谢谢!

最佳答案

问题是,有时您处理的文件没有以 UNCONVOLVED INTEGRATED RADIANCE 开头的行。 outfloat 变量永远不会被绑定(bind),因此当 uncovext 中的 for 循环终止时,您的 print 语句会失败,因为引用的变量不可用。以下代码应显示如何解决该问题。

import glob
import os
import Tkinter
import tkFileDialog


def main():
    root = Tkinter.Tk()
    root.withdraw()
    dir_path = tkFileDialog.askdirectory()
    os.chdir(dir_path)
    for file_path in glob.glob('*.tp6'):
        uncovext(file_path)


def uncovext(file_path):
    for line in open(file_path):
        if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
            text = line[36:47]
            number = float(text) * 10000
            print('%.3f' % number)
            print(file_path)


if __name__ == '__main__':
    main()

关于python - 为具有相同扩展名的多个文件运行脚本。获取 'UnboundLocalError',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35461468/

相关文章:

python - 如何在 Google Colab 中缓存 Python 变量

python - flask socket io无法正常工作(Windows 7和10)anaconda和python 3.7

windows - VB6 Dir ("*.dot") 在一台服务器上通配找到 .dotx,但在另一台服务器上找不到

python - SQLAlchemy FK ondelete 不限制

python - 在 Pandas 中转换日期时间列的快速方法

python - 在 python 中使用 glob.glob 排序

c - POSIX:glob() 只找到第一个匹配项

python - 过滤目录中的所有文件以查找与多个正则表达式匹配的单词

Python文件重命名语法错误

python - 需要一种使用 Python 将图像文件加载到 Mac 剪贴板的方法