Python中检查文本文件是否为空

6
有没有一种方法在Python中检查文本文件是否为空,而不使用os?
目前我尝试过的方法:
x = open("friends.txt")
friendsfile = x.readlines()

if friendsfile == None 

但我认为这不是正确的方式。

为什么你不能使用操作系统? - Radan
解决方案在@Andy提供的链接中。重复已确认。 - David Guyon
2
不,我认为那个链接上没有解决方案,请注意他不想使用操作系统。 - Radan
1
如果你只是想检查文件是否为空,那么打开文件来检查它是否为空会占用大量内存。如果文件已经打开,那么你可以使用Andy提供的链接中的答案。 - Radan
1
请注意,如果您将 if friendsfile == None 更改为 if friendsfile == [][] 是空列表,而 readlines 返回一个列表),或者只是 if not friendsfile(因为 [] 被视为 false),则您的解决方案可能会被修复以变得正确。然而,给出的答案肯定更有效率。 - Alex Hall
1个回答

11

我不确定为什么你不会使用os,但是如果你真的想要的话,你可以打开文件并获取第一个字符。

with open('friends.txt') as friendsfile:
    first = friendsfile.read(1)
    if not first:
        print('friendsfile is empty')
    else:
        #do something

使用以下代码将'friends.txt'文件中的内容读入:with open('friends.txt') as friendsfile: if friendsfile == []: print('friendsfile是空的') else: # 在少一行的情况下执行一些操作....... - mrk
错误的答案。如果第一行只是一个新行且文件中没有其他内容,则计为一个,这是正确的。 - greendino
@AbdullahSaid 这样可以吗? - miradulo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接