2011-05-10 144 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"