|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
按照某本Python中的联系写了如下代码,发现在 with open()的时候假如加上参数'a'就报错,不加参数就可以正常运行。
不明白为何如此,另外如果想实现用参数a打开文件,如果文件名不存在就报错,应该如何修改。请各位大神指教,非常感谢。
- print("Give me the filename:")
- filename = input("filename:")
- try:
- with open(filename, 'a') as talks:
- contents = talks.read()
- except FileNotFoundError:
- print("Can't find the file or directory")
- else:
- print(contents)
复制代码
a是写入模式打开,是不可以读取(read)的
如果不加参数,默认是为'rt'的,也就是只读和文本模式,所以可以读取
- >>> f = open('123.txt','a')
- >>> f
- <_io.TextIOWrapper name='123.txt' mode='a' encoding='cp936'>
- >>> f.read()
- Traceback (most recent call last):
- File "<pyshell#17>", line 1, in <module>
- f.read()
- io.UnsupportedOperation: not readable
- >>> f = open('123.txt')
- >>> f
- <_io.TextIOWrapper name='123.txt' mode='r' encoding='cp936'>
- >>> f.read()
- '123'
复制代码
|
|