2011-05-10 70 views
2

嗨即時通訊慢慢地嘗試學習正確的方式來編寫Python代碼。假設我有一個文本文件,我想檢查是否爲空,我想要發生的是程序立即終止並且控制檯窗口顯示錯誤消息(如果確實爲空)。到目前爲止,我所做的是下面寫的。請教我如何一個人應該處理這種情況的正確方法:文件爲空時顯示錯誤消息 - 正確的方法?

import os 

    def main(): 

     f1name = 'f1.txt' 
     f1Cont = open(f1name,'r') 

     if not f1Cont: 
      print '%s is an empty file' %f1name 
      os.system ('pause') 

     #other code 

    if __name__ == '__main__': 
     main() 

回答

1

沒有必要open()文件,只是使用os.stat()

>>> #create an empty file 
>>> f=open('testfile','w') 
>>> f.close() 
>>> #open the empty file in read mode to prove that it doesn't raise IOError 
>>> f=open('testfile','r') 
>>> f.close() 
>>> #get the size of the file 
>>> import os 
>>> import stat 
>>> os.stat('testfile')[stat.ST_SIZE] 
0L 
>>> 
0

的Python的方式來做到這一點是:

try: 
    f = open(f1name, 'r') 
except IOError as e: 
    # you can print the error here, e.g. 
    print(str(e)) 
+0

您可以打開一個空文件而不會收到IOError,該文件只能存在。 – 2011-05-10 17:34:00

+0

確實。那試試..除了保持程序安全的可能「文件未找到」,「讀取權限」等錯誤。 – 2011-05-10 17:40:55

+1

不要說這是不適當的嘗試/除... ...當然是一件重要的事情要做。但問題是如何檢查一個**空**文件,我不明白你的答案如何解決這個問題。 – 2011-05-10 17:45:43

0

也許的this重複。

從原來的答案:

import os 
if (os.stat(f1name).st_size == 0) 
    print 'File is empty!' 
0

如果文件打開成功f1Cont`」的值將是一個文件對象,將不會是假的(即使該文件是空的)。一方法可以檢查如果該文件是空的(一個成功的開放後):

if f1Cont.readlines(): 
    print 'File is not empty' 
else: 
    print 'File is empty' 

0

假設你要讀的文件,如果它有它的數據,我建議在追加更新模式打開它,看到如果文件位置爲零。如果是這樣,文件中沒有數據。否則,我們可以閱讀它。

with open("filename", "a+") as f: 
    if f.tell(): 
     f.seek(0) 
     for line in f: # read the file 
      print line.rstrip() 
    else: 
     print "no data in file"