0

这个问题与这个问题有关:Python app which reads and writes into its current working directory as a .app/exe

我得到了 .txt 文件的路径,但是现在当我尝试打开它并读取内容时,它似乎没有正确提取数据。

以下是相关代码:

def getLines( filename ):
    path = Cocoa.NSBundle.mainBundle().bundlePath()

    real_path = path[0: len(path) - 8]

    print real_path

    f = open(real_path + filename, 'r') # open the file as an object

    if len(f.read()) <= 0:
        lines = {}                  # list to hold lines in the file
        for line in f.readlines():  # loop through the lines
            line = line.replace( "\r", "    " )
            line = line.replace( "\t", "    " )
            lines = line.split("    ")      # segment the columns using tabs as a base
        f.close()                   # close the file object

        return lines

lines = getLines( "raw.txt" )
for index, item in enumerate( lines ):        # iterate through lines
    # ...

这些是我得到的错误:

  • 30/09/2012 10:28:49.103 [0x0-0x4e04e].org.pythonmac.unspecified.main: for index, item in enumerate(lines): # 遍历行
  • 30/09/2012 10:28:49.103 [0x0-0x4e04e].org.pythonmac.unspecified.main: TypeError: 'NoneType' 对象不可迭代

我有点理解这些错误的含义,但是我不确定为什么要标记它们,因为如果我使用它而不是以 .app 形式运行我的脚本,它就不会出现这些错误并且可以很好地提取数据。

4

1 回答 1

4

如果不重置读取指针,您将无法读取文件两次。此外,您的代码会主动阻止您的文件被正确读取。

您的代码当前执行此操作:

f= open(real_path + filename, 'r')  # open the file as an object

if len(f.read()) <= 0:
    lines = {}                  # list to hold lines in the file
    for line in f.readlines():  # loop through the lines

.read()语句可以一次将整个文件读入内存,从而导致读指针移动到末尾。循环.readlines()不会返回任何内容。

但是,如果您的.read()调用没有读取任何内容,您也只能运行该代码。您基本上是在说:如果文件为空,请阅读这些行,否则不要阅读任何内容。

最后,这意味着您的getlines()函数总是返回None,后来导致您看到的错误。

完全松开if len(f.read()) <= 0:

f= open(real_path + filename, 'r')  # open the file as an object

lines = {}                  # list to hold lines in the file
for line in f.readlines():  # loop through the lines

然后,您无需做任何事情,lines = {}因为对于文件中的每一行,您都替换lines变量:lines = line.split(" ")。您可能打算改为创建一个列表,然后附加:

f= open(real_path + filename, 'r')  # open the file as an object

lines = []              # list to hold lines in the file
for line in f.readlines():  # loop through the lines
    # process line
    lines.append(line.split("    "))

另一个提示:real_path = path[0: len(path) - 8]可以重写为real_path = path[:-8]. 不过,您可能想查看os.path模块来操纵您的路径;我怀疑os.path.split()那里的电话会更好,更可靠地为您服务。

于 2012-09-30T09:43:30.910 回答