Python语言的文件操作
小标 2018-11-14 来源 : 阅读 969 评论 0

摘要:本文主要向大家介绍了Python语言的文件操作,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

本文主要向大家介绍了Python语言的文件操作,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

1、 读写文件#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/1/25 20:49
# @Author  : zhouyuyao
# @File    : demonWrite.py
# PyCharm 2017.3.2 (Community Edition)
# Build #PC-173.4127.16, built on December 19, 2017
# JRE: 1.8.0_152-release-1024-b8 amd64
# JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
# Windows 10 10.0
# Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) 
# [MSC v.1900 64 bit (AMD64)] on win32
if __name__== "__main__":
    filename = input("Please input the name of file:")
    f = open(filename,"w")     # 以写的形式打开一个文件
    while 1:         # 1 的效率是最高的
        context = input("Please input context('EOF' will close file): ")
        if context == "EOF":
            f.close()
            break
        else:
            f.write(context)
            f.write("\n")
    fRead = open(filename)
    readContext = fRead.read()
    print("------------start-------------")
    print(readContext)
    print("-------------end--------------")
    fRead.close()运行结果:Please input the name of file:z.log
Please input context('EOF' will close file): hello
Please input context('EOF' will close file): the weather is cool
Please input context('EOF' will close file): you have wear more clothes
Please input context('EOF' will close file): EOF
------------start-------------
hello
the weather is cool
you have wear more clothes
-------------end--------------2、 读取文件方法import codecs
ENCODING = "utf-8"       # 字符集
f = open("z.log",encoding=ENCODING)
print(f.name)            # 文件名
print(f.readline())      # 读取成列表的形式
print(f.readlines())     # 读取成列表的形式
with codecs.open("z.log","r",encoding=ENCODING) as f:
    print(f.read())3、 编码问题编码:支持中文的编码:utf-8,gbk,gb2312decode  解码encode  编码在Python2中不定义代码的编码排头,在内容中出现中文时会报错。Python默认将代码文件内容当做ASCII编码处理,但是ASCII编码不存在中文,因为则会抛出异常。解决问题之道就是要让Python之道文件中使用的是什么编码形式,对于中文,可以用的常见编码有utf-8,gbk和gb2312等,只需在代码文件的最前端添加如下内容即可:# -*- coding:utf-8 -*-Python转码的过程:原有编码 ——> Unicode编码 ——> 目的编码python会自动将带中文的字符串解码成Unicode,然后再编码成gbk,因为解码是字典进行的,如果没有指明解码方式,就会使用sys,defaultencoding指明的方式来解码。方法一:s.decode("utf-8").encoding("gbk")4、对文件进行排序#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/1/25 23:06
# @Author  : zhouyuyao
# @File    : sortUIDPasswd.py
# PyCharm 2017.3.2 (Community Edition)
# Build #PC-173.4127.16, built on December 19, 2017
# JRE: 1.8.0_152-release-1024-b8 amd64
# JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
# Windows 10 10.0
# Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) 
# [MSC v.1900 64 bit (AMD64)] on win32
import codecs
file = "passwd"
sortfile = "sortpasswd.txt"
filecontext = []
sortuid = []
with codecs.open(sortfile,"wb") as fsort:
    with codecs.open(file,encoding="utf-8") as f:
        filecontext += f.readlines()
        for line in filecontext:
            sortuid.append(int(line.split(":")[2]))
        sortuid.sort()
        for uid in sortuid:
            for line in filecontext:
                if str(uid) == line.split(":")[2]:
                    print(line)
                    fsort.write(line.encode("utf-8"))python3的新特性对文本和二进制数据作了更为清晰的区分,文本总是Unicode,由str类型表示,二进制则是由bytes类型表示字符串可以encode编码成字节包,而字节包可以decode解码成字符串    

本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程