2024-03-29 14:44:40 发布
网友
我试图打开一个文件并从中读取,如果文件不在那里,我会捕获异常并向stderr抛出一个错误。我的密码是:
for x in l: try: f = open(x,'r') except IOError: print >> sys.stderr, "No such file" , x
但是没有打印到stderr,如果文件名不存在,open是否会创建一个新文件,或者是其他地方的问题?
您有os.path.exists函数:
import os.path os.path.exists(file_path)
返回布尔值
试试这个:
from __future__ import print_statement import sys if os.path.exists(x): with open(x, 'r') as f: # Do Stuff with file else: print("No such file '{}'".format(x), file=sys.stderr)
这里的目标是尽可能清楚发生了什么。我们首先通过调用os.path.exists(x)来检查文件是否存在。这将返回True或False,允许我们在if语句中简单地使用它。
os.path.exists(x)
if
从那里你可以打开文件阅读,或处理退出你喜欢。使用Python3样式的打印函数可以显式声明输出的位置,在本例中是stderr。
对我有用。为什么不能使用os.path.exists()
for x in l: if not os.path.exists(x): print >> sys.stderr , "No such file", x
您有os.path.exists函数:
返回布尔值
试试这个:
这里的目标是尽可能清楚发生了什么。我们首先通过调用
os.path.exists(x)
来检查文件是否存在。这将返回True或False,允许我们在if
语句中简单地使用它。从那里你可以打开文件阅读,或处理退出你喜欢。使用Python3样式的打印函数可以显式声明输出的位置,在本例中是stderr。
对我有用。为什么不能使用os.path.exists()
相关问题 更多 >
编程相关推荐