文件为空时显示错误消息的正确方式?

2024-10-01 09:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 方法代码import程序消息ifosmain
3条回答

可能是this的副本。在

从最初的答案:

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

Python的方法是:

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

不需要open()该文件,只需使用^{}。在

>>> #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
>>>

相关问题 更多 >