...:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-19-bf09fccabcc0> in <module>()
1
----> 2 mystr = myfile.read(3)
3 print(mystr)
4
5 #这样就把abc读出来了
NameError: name 'myfile' is not defined
In [20]: #今天这节课是适应Spyder或Python的,所以所有错误一律不管。
In [21]: #读完第一次后,我们要加入一些代码:
In [22]: myfile.seek(0,0)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-22-7dc147563182> in <module>()
----> 1 myfile.seek(0,0)
NameError: name 'myfile' is not defined
In [23]: #这样就能把指针重置了。
In [24]: #现在,在你的txt文件里另起一行,输入“aaaccc”。
In [25]: #接下来,我们新建一个文件:读取文件.py
In [26]: #接下来,我们在里面输入:
In [27]: myfile = open('1.txt','r')
...: mystr = myfile.readline()
...: print(mystr)
...:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-27-d0bab098bb6c> in <module>()
----> 1 myfile = open('1.txt','r')
2 mystr = myfile.readline()
3 print(mystr)
4
FileNotFoundError: [Errno 2] No such file or directory: '1.txt'
In [28]: #在运行后,你会发现,它会把 1.txt里面的第一行全部提取出来。
In [29]: #在win里面,Python会一直往下读文件,直到遇到换行符:\r , \n
In [30]: #也可以是这个“结束符”:EOF(文件的末尾标识符)
In [31]: #接下来,你在“读取文件.py”里面输入:
In [32]: mystr = myfile.readline()
...: print(mystr)
...: mystr = myfile.readline()
...: print(mystr)
...: mystr = myfile.readline()
...: print(mystr)
...:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-32-7e20e94701c3> in <module>()
----> 1 mystr = myfile.readline()
2 print(mystr)
3 mystr = myfile.readline()
4 print(mystr)
5 mystr = myfile.readline()
NameError: name 'myfile' is not defined
In [33]: #然后运行,你会发现它是这样呈现的:
In [34]: # abcdefg
...:
...: # 123456
...:
...: # aaasss
...:
In [35]: #虽然我们没有设置换行符,但是print里面是自带了换行的。
In [36]: #如果我们不需要:
In [37]: #将 print(mystr) 改成: print(mystr,end='')
In [38]: #
In [39]: #接下来,我们再创建一个文件:读取文件2.py
In [40]: #记住啊,这上述四个文件都要保存在刚开始的“文件操作”文件夹里。
In [41]: #但是像之前那样一行一行地读太麻烦了,所以,我们Python里面有个非常简便的代码。
In [42]: #在“读取文件2.py”中输入:
In [43]: myfile = open('1.txt','r')
...: mystr = myfile.readlines()
...:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most