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设计】。

相关文章

详解Django框架中用context来解析模板的方法

你需要一段context来解析模板。 一般情况下,这是一个 django.template.Context 的实例,不过在Django中还可以用一个特殊的子类, django.templ...

python获取中文字符串长度的方法

如下所示: print len('哈哈'.decode('utf-8')) #unicode格式 print len('哈哈') #utf-8格式 以上这篇python获取中文字符...

Ubuntu安装Jupyter Notebook教程

Ubuntu安装Jupyter Notebook教程

一.Jupyter介绍 Jupyter Notebook是一个交互式笔记本,支持运行40多种编程语言。Jupyter Notebook 的本质是一个 Web 应用程序,便于创建和共享文学...

python实现对列表中的元素进行倒序打印

python实现对列表中的元素进行倒序打印

1.案例要求: """有列表["a", "d", "f", "j","z","Z","1"],对列表进行倒序,打印结果为["1","Z","z","j","f","d",""a]""...

使用python进行拆分大文件的方法

使用python进行拆分大文件的方法

python按指定行数把大文件进行拆分 如图大文件有7000多万行,大小为16G 需要拆分成多个200万行的小文件 代码如下: # -*- coding:utf-8 -*- fro...