您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python 3.6 读取并操作文件内容

2024/6/29 2:16:49发布31次查看
下面为大家分享一篇python 3.6 读取并操作文件内容的实例,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧
所使用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读取文本数据并转化为dataframe格式的方法详解
python读取word中的文本内容
以上就是python 3.6 读取并操作文件内容的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product