Python的类型与运算-文件(四)
因为w方式对以存在的文件会清楚后写入,但有的时候我们不想覆盖原有的
文件,这个时候我们可以使用如下方式:
>>> if not os.path.exists('somefile'):
... with open('somefile', 'wt') as f:
... f.write('Hello\n')
... else:
... print('File already exists!')
...
>>> if not os.path.exists('somefile'):
... with open('somefile', 'wt') as f:
... f.write('Hello\n')
... else:
... print('File already exists!')
...
File already exists!
这里我们也有别的方法可以用来判断是否文件存在,不存在时写入(此方法
紧在Python3.x可以使用):
>>> with open('somefile2','xt') as f:
... f.write('Hello\n')
...
6 >>> with open('somefile2','xt') as f:
... f.write('Hello\n')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile2'
当我们需要判断是文件,还是目录的时候,可以引用os.path模块。