2015-05-20 73 views
0

實施的ReadLine()如果我們考慮在Python

f=open('foo.txt') 
x= f.readline() 
print x 

然後我們拿到文件foo.txt的第一線。

現在考慮:

<code> 
f=open('foo.txt') 
while (x = f.readline()) != '': # Read one line till EOF and do something 
    .... do something 
f.close() 
</code> 

這在

x=f.readline(). 

給出了一個語法錯誤,我是比較新的Python和我想不通的問題。一個經常遇到這樣的表達在C.提前

感謝

+1

在Python中,賦值不是一個表達式,不能在條件中使用。你想用這個達到什麼目的?你有沒有嘗試'爲f在f:'? –

+0

是的,我知道f中有'for x:'但我只想看看C類構造是否可行。表達與分配闡明瞭它。比你! – DBS

回答

1

我猜你有答案這裏What's perfect counterpart in Python for "while not eof"

總之你可以檢查線路是否仍然這樣

每個循環有效
with open(filename,'rb') as f: 
    while True: 
     line=f.readline() 
     if not line: break 
     process(line) 

或者你可以使用內置的功能蟒蛇遍歷文件中像這樣

with open('file') as myFile: 
    for line in myFile: 
     do_something()