Skip to main content
 首页 » 编程设计

python之文件为空时显示错误消息之正确的方法

2025年05月04日7cyq1162

嗨,我正在慢慢尝试学习编写 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() 

请您参考如下方法:

无需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 
>>>