Using input() implies Python 3, recent Python 3 versions have made the IOError exception deprecated (it is now an alias for OSError). So assuming you are using Python 3.3 or later:
First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition. You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.
也就是说,你可以按照 That One Random 矬子的建议来做,使用 try: 。实际上,根据蟒蛇的座右铭“请求原谅比请求许可更容易”,这就是提议的方式。
但是,你也可以很容易地测试是否存在:
import os
# open file for reading
fn = raw_input("Enter file to open: ")
if os.path.exists(fn):
fh = open(fn, "r")
else:
fh = open(fn, "w")
import os
if not os.path.exists('/tmp/test'):
os.mknod('/tmp/test')
更新 :
正如 Cory Klein所提到的,在 Mac OS 上使用 os.mknod()需要一个 root 权限,所以如果您是 Mac OS 用户,您可以使用 > open () < a href = “ https://docs.python.org/3/library/function tions.html # open”rel = “ noReferrer”> open () 而不是 os.mknod()
import os
if not os.path.exists('/tmp/test'):
with open('/tmp/test', 'w'): pass
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in (over)write mode
[it overwrites the file if it already exists]
r+ open an existing file in read+write mode
a+ create file if it doesn't exist and open it in append mode
'''
例如:
file_name = 'my_file.txt'
f = open(file_name, 'a+') # open file in append mode
f.write('python rules')
f.close()
I hope this helps. [FYI am using python version 3.6.2]