python文件操作

涉及文本操作就会涉及到编码解码问题,编码方式的历史大致为ASCII ->gb2312->unicode->utf-8,期间具体详细信息可以百度
来个编码解码的小例子先:

bytes = '张三'.encode('GBK')
print(bytes)
print(type(bytes))
byte_utf8 = "张三".encode('utf-8')
print(byte_utf8)
string = bytes.decode('GBK')
print(string)
string = byte_utf8.decode("GBK")
print(string)

b'\xd5\xc5\xc8\xfd'

b'\xe5\xbc\xa0\xe4\xb8\x89'
张三
寮犱笁

可以发现,编码解码格式不一致可能会出现乱码,encode表示编码

  • 文件操作流程
    1.打开文件,得到文件句柄并赋值给一个变量
    2.通过句柄对文件进行操作
    3.关闭文件

简单格式如下:

f=open('test.txt',encoding='utf-8')   #打开文件
data=f.read()            #文件操作
print(data)
f.close()          #关闭文件
  • open()函数的具体用法:
    open函数最常用的使用方法如下:文件句柄 = open('文件路径', '模式',编码方式)。
  1. 文件路径
    文件路径:主要有两种,一种是使用相对路径,想上面的例子就是使用相对路径。另外一种就是绝对路径,像' C:/Users/shu/Desktop/python/test.txt'
  2. 打开模式
  • 关闭文件
    不要小看这一步,因为我们读取文件是把文科读取到内存中的,如果我们没关闭它,它就会一直占用系统资源,而且还可能导致其他不安全隐患。还有一种方法可以让我们不用去特意关注关闭文件。那就是 with open()

  • 打开文件的类型介绍
    可以打开文本文件和二进制文件,文本文件本质上存储时,也是二进制文件。但可以用文本编辑器查看。二进制文件,无法通过文本编辑器查看


  • 读文件三种方法

  1. read()
    特点是:读取整个文件,将文件内容放到一个字符串变量中。
    劣势是:如果文件非常大,尤其是大于内存时,无法使用read()方法。
    实例如下:
file = open('兼职模特联系方式.txt', 'r')  # 创建的这个文件,也是一个可迭代对象

try:
    text = file.read()  # 结果为str类型
    print(type(text))
    print(text)
finally:
    file.close()
"""

吴迪 177 70 13888888
王思 170 50 13988888
白雪 167 48 13324434
黄蓉 166 46 13828382
"""
>>> file = open('兼职模特联系方式.txt', 'r')
>>> a = file.read()
>>> a
'吴迪 177 70 13888888\n王思 170 50 13988888\n白雪 167 48 13324434\n黄蓉 166 46 13828382'

read()直接读取字节到字符串中,包括后面的换行符

  1. readline()方法
    特点:readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存
    缺点:比readlines慢得多
file = open('兼职模特联系方式.txt', 'r')

try:
    while True:
        text_line = file.readline()
        if text_line:
            print(type(text_line), text_line)
        else:
            break
finally:
    file.close()
"""
 吴迪 177 70 13888888

 王思 170 50 13988888

 白雪 167 48 13324434

 黄蓉 166 46 13828382
"""
>>> file = open('兼职模特联系方式.txt', 'r')
>>> a = file.readline()
>>> a
'吴迪 177 70 13888888\n'

readline() 读取整行,包括行结束符,并作为字符串返回

  1. readlines()方法
    特点:一次性读取整个文件;自动将文件内容分析成一个行的列表。
    缺点:若一个文件特别大,name一次性将文件都读入内存,容易奔溃
file = open('兼职模特联系方式.txt', 'r')

try:
    text_lines = file.readlines()
    print(type(text_lines), text_lines)
    for line in text_lines:
        print(type(line), line)
finally:
    file.close()
"""
 ['吴迪 177 70 13888888\n', '王思 170 50 13988888\n', '白雪 167 48 13324434\n', '黄蓉 166 46 13828382']
 吴迪 177 70 13888888

 王思 170 50 13988888

 白雪 167 48 13324434

 黄蓉 166 46 13828382
"""
>>> file = open('兼职模特联系方式.txt', 'r')
>>> a = file.readlines()
>>> a
['吴迪 177 70 13888888\n', '王思 170 50 13988888\n', '白雪 167 48 13324434\n', '黄蓉 166 46 13828382']

以上部分内容摘自博客:https://www.cnblogs.com/xiugeng/p/8635862.html

  • 文件写方法:write、writelines
    write和writelines的区别
    1 write()需要传入一个字符串做为参数,否则会报错
    2 writelines()既可以传入字符串又可以传入一个字符序列,并将该字符序列写入文件
    注意 :writelines必须传入的是字符序列,不能是数字序列
    如:list_1023 = [1,2,3,4,5]
    报错:TypeError: write() argument must be str, not list
    其余用法很多类似于读操作

附上文件操作的作业:

# 作业1:创建文件:data.txt,一共10000行,每行存放一个1-100间的整数。
# 作业2:找出文件中数字出现最多的十个数字。
# 写入到文件mostNum.txt中。可用collections.counter
from random import randint
from collections import Counter
count_list = Counter(['b', 'a', 'a', 'b', 'a', 'c', 'b', 'b'])
print(count_list)

count_tuple = Counter((1,4,3,4,1,3,2,2,1))
print(count_tuple)

with open('data.txt', 'w') as f:
    for i in range(10000):
        f.write(str(randint(1,101)) + '\n')

with open('data.txt', 'r') as f:
    content = []
    line = f.readline()
    while line:
        content.append(line[:-1])
        line = f.readline()
    count_list = Counter(content)
    most_count_list = count_list.most_common(10)

    print(most_count_list)
    for i in range(10):
        print(most_count_list[i][0])

Counter({'b': 4, 'a': 3, 'c': 1})
Counter({1: 3, 4: 2, 3: 2, 2: 2})
[('86', 124), ('48', 122), ('72', 121), ('98', 121), ('5', 115), ('24', 115), ('68', 114), ('13', 114), ('93', 114), ('27', 112)]
86
48
72
98
5
24
68
13
93
27

你可能感兴趣的:(python文件操作)