pycharm配置python环境的方法:
直接的写入数据是不行的,因为默认打开的是’r’ 只读模式
>>> f.write(‘hello boy’)
traceback (most recent call last):
file “”, line 1, in
ioerror: file not open for writing
>>> f
应该先指定可写的模式
>>> f1 = open(‘/tmp/test.txt’,’w’)
>>> f1.write(‘hello boy!’)
但此时数据只写到了缓存中,并未保存到文件,而且从下面的输出可以看到,原先里面的配置被清空了
[root@node1 ~]# cat /tmp/test.txt
[root@node1 ~]#
关闭这个文件即可将缓存中的数据写入到文件中
>>> f1.close()
[root@node1 ~]# cat /tmp/test.txt
[root@node1 ~]# hello boy!
注意:这一步需要相当慎重,因为如果编辑的文件存在的话,这一步操作会先清空这个文件再重新写入。那么如果不要清空文件再写入该如何做呢?
使用r 模式不会先清空,但是会替换掉原先的文件,如下面的例子:hello boy! 被替换成hello aay!
>>> f2 = open(‘/tmp/test.txt’,’r ‘)
>>> f2.write(‘\nhello aa!’)
>>> f2.close()
[root@node1 python]# cat /tmp/test.txt
hello aay!
如何实现不替换?
>>> f2 = open(‘/tmp/test.txt’,’r ‘)
>>> f2.read()
‘hello girl!’
>>> f2.write(‘\nhello boy!’)
>>> f2.close()
[root@node1 python]# cat /tmp/test.txt
hello girl!
hello boy!
可以看到,如果在写之前先读取一下文件,再进行写入,则写入的数据会添加到文件末尾而不会替换掉原先的文件。这是因为指针引起的,r 模式的指针默认是在文件的开头,如果直接写入,则会覆盖源文件,通过read() 读取文件后,指针会移到文件的末尾,再写入数据就不会有问题了。这里也可以使用a 模式
>>> f = open(‘/tmp/test.txt’,’a’)
>>> f.write(‘\nhello man!’)
>>> f.close()
>>>
[root@node1 python]# cat /tmp/test.txt
hello girl!
hello boy!
hello man!