我对Python是新手,在C++编程方面经验很少。我看到了this问题,但它没有解决我的问题。在Python 2.7.9, 64-bit AMD, Windows 7 Ultimate, NTFS, administrator privileges & no "read only" attribute on file to be read.
我想创建一个满足特定条件的字符串列表,这些字符串是文件的行(请参见记事本.cc/diniko93)。所以我写了以下函数-def makeLineList( filePtr, ptr ):
lines = []
while True:
s = filePtr.readline()
if not s=="":
s = s[3:]
s = s.split()
if s[0].isdigit():
print("O")
lines.append(s)
elif s[0] in {"+", "-"}:
print("U")
lines.append(s)
else:
print("none")
break
filePtr.seek(ptr, 0); #I did this to restore file pointer, so other functions accessing this file later don't misbehave
return lines
我使用的两个可能的main()类(请原谅我对python一无所知)实体是-
^{pr2}$
另一个-osrc = open("./testStage1.txt", 'r')
osrc.seek(291, 0)
L = makeLineList( osrc, osrc.tell())
print "".join(L)
osrc.close()
两次终端上的输出都是令人失望的none
请注意以上代码是重现问题所需的最低要求,而不是整个代码。在
编辑:
根据@avenet的建议,我在google上尝试在代码中使用iter(__next__obj.next()在python3.3+中使用next(obj)),但问题仍然存在,即使我从函数内部调用next(osrc),我也无法读取下一行代码检查这两个片段version2next只在main()中使用-不调用ish part transform_line函数。调用next()3次会产生理想的/预期的输出,但是
version3我得到了一个列表索引超出范围的错误,即使列表[0]确实有一个数字
编辑2:我尝试在函数中使用scope check作为if not osrc in locals():在下一行中使用适当的缩进print("osrc not reachable")。输出是osrc not reachable。我还尝试使用临时tLib.py公司但结果是一样的。为什么osrc在这两种情况下都不可用?在
编辑3:因为问题似乎在范围之内。
因此,为了避免传递文件变量-创建一个唯一的目的是读取一行的函数。是否下一行的决定取决于isLineUtility()等函数的返回值def isLineUseful( text, lookFor ):
if text.find(lookFor)!=-1:
return 1
else:
return 0
def makeList( pos, lookFor ):
lines = []
with open("./testStage1.txt", 'r') as src:
src.seek(pos)
print(src.read(1))
while True:
line = next(src)
again = isLineUseful(line, lookFor)
if again==0:
src.seek(pos)
break
else:
lines.append(line)
return lines
t = makeList(84, "+")
print "\n".join(t)
试过了,在这个上面效果很好(记事本.cc/diniko93)示例testStage1.txt。在
因此,我的编程问题得到了解决(感谢responders:D)&;我将此标记为已回答,但发布了一个关于readline()&;__next__的异常/行为的新问题。在
另外,我还在学习python的方法,所以如果您能推荐一个更适合我上面代码的pythonic和idomatic版本,我将非常高兴。在