我写了一个脚本来读取 python 中的文本文件。
这是代码。
parser = argparse.ArgumentParser(description='script')
parser.add_argument('-in', required=True, help='input file',
type=argparse.FileType('r'))
parser.add_argument('-out', required=True, help='outputfile',
type=argparse.FileType('w'))
args = parser.parse_args()
try:
reader = csv.reader(args.in)
for row in reader:
print "good"
except csv.Error as e:
sys.exit('file %s, line %d: %s' % (args.in, reader.line_num, e))
for ln in args.in:
a, b = ln.rstrip().split(':')
我想检查文件是否存在并且不是空文件,但这段代码给我一个错误。
我还想检查程序是否可以写入输出文件。
命令:
python script.py -in file1.txt -out file2.txt
错误:
good
Traceback (most recent call last):
File "scritp.py", line 80, in <module>
first_cluster = clusters[0]
IndexError: list index out of range
原文由 user3573959 发布,翻译遵循 CC BY-SA 4.0 许可协议
要检查文件是否存在且不为空,您需要调用
os.path.exists
和os.path.getsize
的组合以及“and”条件。例如:As an alternative , you may also use
try/except
with theos.path.getsize
(without usingos.path.exists
) because it raisesOSError
if the file does not存在或您没有访问该文件的权限。例如:来自 Python 3 文档的 参考
os.path.getsize()
将:对于空文件,它将返回
0
。例如:os.path.exists(path)
将: