这个问题与此问题有关: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
# ...
这些是我得到的错误:
我有点理解错误的意思但是我不确定它们为什么被标记,因为如果我用它运行我的脚本而不是.app形式它不会得到这些错误并提取数据。
答案 0 :(得分: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
module来操纵您的路径;我怀疑os.path.split()
电话会在那里更好,更可靠。