在 Python 中检查空文件或丢失文件的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17747330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to check for empty or missing file in Python
提问by TheRogueWolf
I want to check both whether a file exists and, if it does, if it is empty.
我想检查文件是否存在,如果存在,是否为空。
If the file doesn't exist, I want to exit the program with an error message.
如果文件不存在,我想退出程序并显示错误消息。
If the file is empty I want to exit with a different error message.
如果文件为空,我想以不同的错误消息退出。
Otherwise I want to continue.
否则我想继续。
I've been reading about using Try: Except: but I'm not sure how to structure the code 'Pythonically' to achieve what I'm after?
我一直在阅读有关使用 Try: except: 的信息,但我不确定如何以“Python 方式”构建代码以实现我所追求的目标?
Thank you for all your responses, I went with the following code:
感谢您的所有回复,我使用以下代码:
try:
if os.stat(URLFilePath + URLFile).st_size > 0:
print "Processing..."
else:
print "Empty URL file ... exiting"
sys.exit()
except OSError:
print "URL file missing ... exiting"
sys.exit()
采纳答案by mgilson
回答by Jakob Bowyer
os.path.existsand other functions in os.path.
os.path.exists和 os.path 中的其他函数。
As for reading,
至于阅读,
you want something like
你想要类似的东西
if not os.path.exists(path):
with open(path) as fi:
if not fi.read(3): #avoid reading entire file.
print "File is empty"
回答by Tim Pietzcker
How about this:
这个怎么样:
try:
myfile = open(filename)
except IOError: # FileNotFoundError in Python 3
print "File not found: {}".format(filename)
sys.exit()
contents = myfile.read()
myfile.close()
if not contents:
print "File is empty!"
sys.exit()
回答by Roland Smith
Try this:
尝试这个:
import os
import sys
try:
s = os.stat(filename)
if s.st_size == 0:
print "The file {} is empty".format(filename)
sys.exit(1)
except OSError as e:
print e
sys.exit(2)