Created
March 9, 2019 07:29
-
-
Save caoya171193579/8ed6da74229000a984ea70683dbc0b8d to your computer and use it in GitHub Desktop.
进阶
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
【文件的打开和创建】 | |
【文件读取】 | |
【文件写入】 | |
【内容查找和替换】 | |
【文件删除,复制,重定名】 | |
【目录操作】 | |
########################################### | |
python 文件读写: | |
进行文件读写的函数是open 或 file(类) | |
open : (read(): 查看 ,close():关闭。 关闭以后就整个文件关闭了。) #方法 定义一个变量wen = open('文件绝对路径') | |
>>> wen = open('/root/wenjian.txt') | |
>>> | |
>>> wen #变量就会返回一个我们所看文件的对象。 | |
<open file '/root/wenjian.txt', mode 'r' at 0x7f3f64afe540> | |
>>> | |
>>> wen.read() #使用read()参数读取、 查看文件内的内容。 | |
'192.168.1.108\n\na am tom\n\n123456\n' | |
>>> | |
>>> wen.close() #使用close()参数关闭文件,就不会再看的到了 | |
>>> | |
>>> wen.read() | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
ValueError: I/O operation on closed file | |
>>> | |
########################################### | |
类后续还会再讲!!! | |
file: 类 (用法和open函数同样,read()打开,close()关闭)。 | |
>>> wen = file('/root/wenjian.txt') | |
>>> | |
>>> wen.read() | |
'192.168.1.108\n\na am tom\n\n123456\n' | |
>>> wen.close() | |
>>> wen.read() | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
ValueError: I/O operation on closed file | |
>>> | |
############################################## | |
mode : (谋得)#模式 | |
文件读写的模式有很多 | |
r #只读 | |
r+ #可读写 | |
w #写入,先删除原文件,再重新写入,如果文件没有则创建。 | |
w+ #读写,先删除原文件,再重新写入,如果文件没有则创建。(可以写入输出) | |
a #写入:在文件末尾追加新的内容,文件不存在,则创建。 | |
a+ #读写: 在文件末尾追加新的内容,文件不存在,则创建。 | |
b #打开二进制的文件。可以与r,w,a,+结合使用。(写入图片,或者查看图片文件,要加上b,如果不加打开的就是损坏文件) | |
U #支持所有的换行符号。酋\r" , "\n" , "\r\n" | |
######################################### | |
用w参数模式的时候,一定要注意,因为它会先把源文件删除!!!!!!可以单独重新写一个新文件。 | |
write(): 文件写入的参数。 | |
#先定义变量来打开文件,w+模式是删除文件里所有内容。 | |
>>> fnew = open('/root/wenjian.txt',"w+") | |
>>> | |
>>> fnew | |
<open file '/root/wenjian.txt', mode 'w+' at 0x7f369d2df540> | |
#write参数是写入文件内容。 | |
>>> fnew.write('nihao \nlaji') | |
>>> | |
#未关闭文件是看不到文件内容的 | |
>>> fnew.read() | |
'' | |
>>> fnew.close() #关闭打开的文件,源内容已经删除,现在是新内容。 | |
 | |
# a 可写, a+可读可写 | |
文件每次打开都有一个隐形的由标或者指针,指针的位置就在开头的第一个数值或者字母那里依次往后读取, 隐形的指针读取完数据以后,才会显示出来我们要看到的数据,隐形指针就到了数值的最后位置,添加数据就添加到了最后。 | |
>>> fnew = open('/root/wenjian.txt',"a+") | |
>>> | |
>>> fnew.read() | |
'nihao \nlaji' | |
>>> | |
>>> fnew.write('\nwobuhao') | |
>>> | |
>>> fnew.read() | |
'' | |
>>> fnew.close() | |
 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment