Python 基础 --- 文件操作

三元运算: 是对简单条件语句的简写

>>> a = 2
>>> b =4 
>>> val = a if a> b else b
>>> val
4

文件处理

1.文件的读取

f = open(file="bb.txt",mode = 'r',encoding="gbk")  #注意文件本身的字符集
data = f.read()
print (data)
f.close()

f = open(file = 'bb.txt',mode ='r',encoding = 'gbk' )
for line in f:
    print (line)
f.close()
打印出的结果行之间会有空行

 以二进制模式读取
 f = open(file="bb.txt.txt",mode = 'rb')
 b'\xb7\xbf\xb4\xfb\xca\xd7\xb8\xb6\xb6\xe0\xc9\xd9\xb7\xb6\xb5\xc2\xc8\xf8\xb7\xb6\xb5\xc2\xc8\xf8\r\n '

2.智能检测编码

# _*_ coding:utf-8_*_
import chardet
f = open(file="bb.txt",mode = 'rb')
data = f.read()
print (data)
f.close()
result = chardet.detect(data)  # 检测data 内容的字符集
print (result) 
    {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}
print (data.decode('gb2312'))  # 根据字符集解码出对应的内容
    房贷首付多少

3.写模式操作

w 是创建,如果有同名文件会覆盖
f = open('write.txt','w')
f.write("---是我的海---")
f.close()

# 如果是以二进制格式写入,则下面要指定写入文件的字符集。
f = open('write.txt','wb')     
f.write("是我的海".encode("utf-8"))
f.close()

4.追加写入(追加到文件尾部)

f = open(file = 'append.txt',mode = 'ab')
f.write("\n是我的海--- 1988 --- DBA".encode('utf8'))
f.close()

5.混合操作:(先读后写)

f = open (file = 'append.txt',mode = 'r+',encoding = 'gbk')
data = f.read()
print ("content",data)
f.write("\n混合模式 2")
print ("content",f.read())
f.close()
可以根据f.tell() 的位置来判定是从哪个位置开始写的。
如果先执行f.read() 操作,则光标会移动到最后,写操作就会追加内容

 6.文件操作的其他方法

 # f.flush()刷新内存数据到磁盘, f.readable() 判断文件是否可读

f = open(file = 'louis.txt',mode = 'a')
f.write('\nreadline +2')
f.flush()
print (f.readable())
f.close()

seek 把光标移动到指定位置,readline() 逐行读取内容

>>> f = open('louis.txt','r')
>>> f.readline()
'kkkkkkkkxx的海+++louislouisxxx\n'
>>> f.readline()
'oooooooo是我的海'
>>> f.readline()
''
>>> f.seek(0)
0
>>> f.readline()
'kkkkkkkkxx的海+++louislouisxxx\n'

# 对于tell 和seek 对应的是字节。read 对应的是字符

>> f = open('seek.txt','r')
>>> f.read()
'是我的海'
>>> f.read(1)
''
>>> f.seek(0)
0
>>> f.read(1)
'是'
>>> f.tell()
2
>>> f.seek(4)
4
>>> f.readline()
'的海'
>>> f.seek(1)
1
>>> f.read()
Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa3 in position 6: incomplete multibyte sequence
>>> f.seek(2)
2
>>> f.read()
'我的海'

f.truncate() #从当前位置向后截断。f.truncate(6) # 从开头到这个地方截断

文件的修改

1.磁盘的方式修改
import os

f_name = 'louis.txt'
f_new = '%s.new' %f_name

old = 'xinxin'
new = 'tingting'

f = open(f_name,'r')
f_new = open(f_new,'w')

for line in f:
    if old in line:
        line = line.replace(old,new)
    f_new.write(line)
f.close()
f_new.close()

os.rename(f_new_name,'louis')

2.内存的方式修改
f = open('louis.txt','r+')
data = f.read()
data = data.replace('xinxin','louis')
f.seek(0)
f.truncate()
f.write(data)
f.close()

 

posted @ 2018-04-01 22:41  Sin-是我的海  阅读(53)  评论(0)    收藏  举报