Python 3.6 读取并操作文件内容的实例

yipeiwu_com6年前Python基础

所使用python环境为最新的3.6版本

Python中几种对文件的操作方法:

将A文件复制到B文件中去(保持原来格式)

读取文件中的内容,返回List列表 (加载本地词典库)

读取文件,返回文件内容

#!/usr/bin/env python
# encoding: utf-8
"""
@author: wugang
@contact: 752820344@qq.com
@software: PyCharm
@file: toolkits_file.py
@time: 2017/3/1 0001 17:01
"""
'''
对文件操作的工具模块
'''
# 1.将A文件复制到B文件中去(保持原来格式)
def copy_file (inputFile, outputFile, encoding):
 fin = open(inputFile, 'r', encoding=encoding) #以读的方式打开文件
 fout = open(outputFile, 'w', encoding=encoding) #以写得方式打开文件
 for eachLiine in fin.readlines(): #读取文件的每一行
 line = eachLiine.strip() #去除每行的首位空格
 fout.write(line + '\n')
 fin.close()
 fout.close()
# 2. 读取文件中的内容,返回List列表 (加载本地词典库)
def read_file_list(inputFile, encoding):
 results = []
 fin = open(inputFile, 'r', encoding=encoding)
 for eachLiine in fin.readlines():
 line = eachLiine.strip().replace('\ufeff', '')
 results.append(line)
 fin.close()
 return results
# 3.读取文件,返回文件内容
def read_file(path):
 with open(path, 'r+', encoding='UTF-8') as f:
 str = f.read()
 return str.strip().replace('\ufeff', '')
def func():
 pass
if __name__ == '__main__':
 copy_file('../data/test1.txt', '../data/text.txt','UTF-8')
 contents = read_file_list('../dict/time.dict','UTF-8')
 print(contents)

以上这篇Python 3.6 读取并操作文件内容的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

修改Python的pyxmpp2中的主循环使其提高性能

引子 之前clubot使用的pyxmpp2的默认mainloop也就是一个poll的主循环,但是clubot上线后资源占用非常厉害,使用strace跟踪发现clubot在不停的poll,...

python使用正则表达式检测密码强度源码分享

复制代码 代码如下:#encoding=utf-8#-------------------------------------------------------------------...

python中Switch/Case实现的示例代码

学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现Switch/Case功能。 使用...

在Python中过滤Windows文件名中的非法字符方法

网上有三种写法: 第一种(所有非法字符都不转义): def setFileTitle(self,title): fileName = re.sub('[\/:*&#...

详解在python操作数据库中游标的使用方法

cursor就是一个Cursor对象,这个cursor是一个实现了迭代器(def__iter__())和生成器(yield)的MySQLdb对象,这个时候cursor中还没有数据,只有等...