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,gb2312

decode 解码
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解码成字符串


 本文转自 归来仍少年 51CTO博客,原文链接:http://blog.51cto.com/shaoniana/2065990


相关文章
|
12天前
|
Python
Python文件操作学习应用案例详解
【4月更文挑战第7天】Python文件操作包括打开、读取、写入和关闭文件。使用`open()`函数以指定模式(如'r'、'w'、'a'或'r+')打开文件,然后用`read()`读取全部内容,`readline()`逐行读取,`write()`写入字符串。最后,别忘了用`close()`关闭文件,确保资源释放。
17 1
|
17天前
|
Python
【python】python跨文件使用全局变量
【python】python跨文件使用全局变量
|
25天前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
21 1
|
30天前
|
存储 并行计算 Java
Python读取.nc文件的方法与技术详解
本文介绍了Python中读取.nc(NetCDF)文件的两种方法:使用netCDF4和xarray库。netCDF4库通过`Dataset`函数打开文件,`variables`属性获取变量,再通过字典键读取数据。xarray库利用`open_dataset`打开文件,直接通过变量名访问数据。文中还涉及性能优化,如分块读取、使用Dask进行并行计算以及仅加载所需变量。注意文件路径、变量命名和数据类型,读取后记得关闭文件(netCDF4需显式关闭)。随着科学数据的增长,掌握高效处理.nc文件的技能至关重要。
109 0
|
1月前
|
Unix Linux 测试技术
Python超详细基础文件操作(详解版)(下)
Python超详细基础文件操作(详解版)
|
1月前
|
存储 JSON 数据库
Python超详细基础文件操作(详解版)(上)
Python超详细基础文件操作(详解版)
|
1月前
|
Python
python中文件和异常处理方法(三)
python中文件和异常处理方法(三)
19 0
|
29天前
|
存储 安全 API
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
74 0
|
1天前
|
存储 Python
用Python实现批量下载文件——代理ip排除万难
用Python实现批量下载文件——代理ip排除万难
|
1天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
20 0