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