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

Python 文件为空时显示错误消息-正确方式?,python,Python,嗨,我正在慢慢地学习编写python代码的正确方法。假设我有一个文本文件,我想检查它是否为空,我想做的是程序立即终止,如果确实为空,控制台窗口会显示一条错误消息。到目前为止,我所做的事情写在下面。请教我如何处理这个案件: import os def main(): f1name = 'f1.txt' f1Cont = open(f1name,'r') if not f1Cont: print '%s is an

嗨,我正在慢慢地学习编写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()
文件,只需使用


蟒蛇式的方法是:

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

根据最初的答复:

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

如果文件打开成功,“f1Cont”的值将是一个文件对象,并且不会为False(即使文件为空)。检查文件是否为空(成功打开后)的一种方法是:

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

假设您要读取文件中是否包含数据,我建议您以追加更新模式打开它,并查看文件位置是否为零。如果是,则文件中没有数据。否则,我们可以阅读它

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"

您可以打开一个空文件而不会出现IOError,该文件只需存在即可。那就试试吧。。Exception确保程序安全,避免可能出现的“文件未找到”、“读取权限”等错误。不要说使用try/except是不合适的……这当然是一件重要的事情。但问题是如何检查一个空文件,我看不出你的答案如何回答这个问题。是的,我的错,误解了这个问题。
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"