【问题标题】:Python .app doesn't read .txt file like it shouldPython .app 不会像应有的那样读取 .txt 文件
【发布时间】:2012-09-30 09:36:03
【问题描述】:

这个问题与这个问题有关: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' object is not iterable

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

【问题讨论】:

  • 请不要使用其他网站粘贴您的代码。虽然这在 IRC 聊天室中可能是一种很好的做法,但在 stackoverflow 上,您最好将相关代码直接粘贴到问题中。
  • 您想在粘贴之前将制表符转换为空格,否则会破坏缩进。

标签: python file .app


【解决方案1】:

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

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

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()) &lt;= 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 module 来操纵您的路径;我怀疑os.path.split() 呼叫会更好、更可靠地为您服务。

【讨论】:

  • 很好的分析和解释-我希望OP感谢您的努力+1
猜你喜欢
  • 2019-09-06
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
相关资源
最近更新 更多