Python中请求操作系统打开一个文件对象:
>>>f = open('C:/Users/huang/Desktop/try.txt','r')
其中的变量 f 便为操作系统传递给Python解释器的文件对象,open() 函数默认的打开方式为’读‘。
在windows中,一般情况下文件的属性名中现实的路径使用的是‘\’斜号,而在Python代码中应该写为‘/’,并且应该写出文件下表(如‘.txt’),这是应该要注意的,否则将会出现如下错误:
In [9]: with open('C:\Users\huang\Desktop\try.txt','r') as f:
...: print f.read()
...:
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-9-d1df363740df> in <module>()
----> 1 with open('C:\Users\huang\Desktop\try.txt','r') as f:
2 print f.read()
3
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\\huang\\Desktop\try.txt'