Python.app没有';不要像应该的那样读取.txt文件

Python.app没有';不要像应该的那样读取.txt文件,python,file,.app,Python,File,.app,这个问题与这个问题有关: 我得到了.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') # o

这个问题与这个问题有关:

我得到了.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
    # ...
def getLines(文件名):
path=Cocoa.NSBundle.mainBundle().bundlePath()
实路径=路径[0:len(路径)-8]
打印真实路径
f=打开(实路径+文件名,'r')#将文件作为对象打开

如果len(f.read())不重置读取指针,则无法读取文件两次。此外,代码会主动阻止文件被正确读取

您的代码当前执行以下操作:

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
然后,您不需要对
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\u path=path[0:len(path)-8]
可以重写为
real\u path=path[:-8]
。不过,您可能希望查看操作路径的方法;我怀疑
os.path.split()
调用对您来说会更好、更可靠。

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

您的代码当前执行以下操作:

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
然后,您不需要对
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\u path=path[0:len(path)-8]
可以重写为
real\u path=path[:-8]
。不过,您可能希望查看操作路径的方法;我怀疑
os.path.split()
调用对您来说会更好、更可靠。

请不要使用其他网站粘贴您的代码。虽然这在IRC聊天室中可能是一种很好的做法,但在stackoverflow上,最好是将相关代码直接粘贴到问题中。不过,如果您想在粘贴到此处之前将制表符转换为空格,则会严重破坏缩进。请不要使用其他网站粘贴代码。虽然这在IRC聊天室中可能是一种很好的做法,但在stackoverflow上,最好将相关代码直接粘贴到问题中。不过,在粘贴到此处之前,您希望将选项卡转换为空格,很好的分析和解释-我希望OP能欣赏这一努力+1伟大的分析和解释-我希望OP能欣赏这一努力+1