[英]readline function returning empty string
我是Python的新手。 很少有C ++編程經驗。 我看到了這個問題,但沒有解決我的問題。
Python 2.7.9、64位AMD,Windows 7 Ultimate,NTFS,管理員特權以及要讀取的文件上沒有“只讀”屬性。
我想創建一個滿足特定條件的字符串列表,這些字符串是文件的行(請參見notepad.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
和我正在使用的2個可能的main()-like(原諒我對python的無知)是-
with open("./testStage1.txt", 'r') as osrc:
osrc.seek(291, 0)
L = makeLineList( osrc, osrc.tell())
print "".join(L)
另一個-
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()
在python 3.3+或next(obj)
2.7)在我的代碼,但問題仍然存在,我無法甚至閱讀下一行如果我從函數內部調用next(osrc)
,請檢查這2個代碼段
編輯2:我嘗試在我的函數內部進行范圍檢查 , if not osrc in locals():
並在下一行使用適當的縮進print("osrc not reachable")
。 並且輸出osrc not reachable
。 我還嘗試了from tLib import transform_line
使用臨時tLib.py中的from tLib import transform_line
,但結果相同。 為什么在兩種情況下osrc都不可用?
編輯3:由於問題似乎是范圍。 因此,為避免傳遞文件變量,請創建一個函數的唯一目的是讀取一行。 是否決定下一行取決於isLineUseful()之類的函數的返回值。
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)
對其進行了嘗試,使其在此(notepad.cc/diniko93)示例testStage1.txt上可以完美運行。
這樣我的編程問題就解決了(感謝響應者:D),我將其標記為已回答,但發布了一個有關readline()
和__next__
的異常/行為的新問題。
PS:我仍在學習python的方法,因此,如果您能為我的代碼建議一個更pythonic和idomatic的版本,我將非常高興。
首先,您沒有使用Python,應該使用它。 使用Python之類的語言的目的是編寫更少的代碼行,以達到其他編程語言(例如C ++或Java)的其他代碼片段的相同結果。
不必將文件指針作為函數參數來讀取文件,您可以在傳遞文件名的函數中直接打開文件。
然后,您可以使用文件名調用此函數,並將列表存儲在最終將要操作的變量中。 如果您不熟悉異常處理,則可以例如使用模塊os
的函數來檢查文件是否已存在: os.path.exists(filename)
。
如果要在當前使用的行中搜索模式,則可以簡單地使用if語句(這樣做的方法很多,這只是一個示例):
if line not in list_of_strings_you_want_not_to_include:
lines.append(line)
如果要檢查模式是否在開頭,則可以在該行上使用startswith
字符串函數:
if not str(line).startswith("+"):
lines.append(line)
如果要跳過一定數量的字符,可以使用seek
功能(因為您正在有效使用)。 這只是一種使用更多代碼行的方法,但仍然非常簡單:
def read_file(filename, _from):
lines = []
try:
with open(filename) as file:
file.seek(_from)
for line in file:
lines.append(line)
except FileNotFoundError:
print('file not found')
return lines
filename = "file.txt"
lines = read_file(filename, 10)
更加容易,您也可以執行此操作,而不是通過所有行顯式地進行迭代:
with open(filename) as file:
file.seek(_from)
return list(file)
或者使用您喜歡的函數readlines
:
with open(filename) as file:
file.seek(_from)
return file.readlines()
在所有行中進行顯式迭代的目的和優點是,您可以在閱讀的正確時機進行大量檢查,並根據需要對行或字符進行任何檢查,因此,我肯定會采用上面建議的第一個選項。
如果要按自己的方式修改行:
def transform_line(line):
if line != "":
if line[0].isdigit():
print("O")
elif line[0] in {"+", "-"}:
print("U")
else:
print("None")
return line
with open("./testStage1.txt", 'r') as osrc:
osrc.seek(291)
lines = [transform_line(line) for line in osrc]
#Do whatever you need with your line list
如果您不想變換線條,請執行以下操作:
with open("./testStage1.txt", 'r') as osrc:
osrc.seek(291)
lines = list(osrc)
#Do whatever you need with your line list
或者,如果您需要在特定條件下停止,則只需實施一個行迭代器:
def line_iterator(file):
for line in file:
if not line[0].isdigit() and not line in ["+", "-"]:
yield line
else:
break
with open("./testStage1.txt", 'r') as osrc:
osrc.seek(291)
lines = list(line_iterator(osrc))
#To skip lines from the list containing 'blah'
lines = [x for x in lines if 'blah' not in line]
#Do whatever you need with your line list
您嘗試處理此輸入:
<P> unnecessart line </P>
<P> Following is an example of list </P>
<P> 1. abc </P>
<P> + cba </P>
<P> + cba </P>
<P> + xyz </P>
現在,在大腦中,您只看到重要的部分,而Python則看到了所有內容。 對於Python(和其他任何編程語言),每一行均以<
開頭。 這就是if
永不匹配的原因。
如果去除了<P>
,請確保也去除空格,因為
1. abc
+ cba
第二行以空格開頭,因此s[0]
不是+
。 要刪除空格,請使用s.trim()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.