Python 3.6 reads and manipulates file contents

不言
Release: 2018-04-23 15:21:07
Original
2023 people have browsed it

The following is an example of reading and manipulating file contents in Python 3.6. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

The python environment used is the latest version 3.6

Several methods of operating files in Python:

Copy file A to file B (keep the original format)

Read the contents of the file and return the List list (load the local dictionary library)

Read the file, Return file content


#!/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)
Copy after login

Related recommendations:

Detailed explanation of how python reads text data and converts it into DataFrame format

Python reads the text content in word

The above is the detailed content of Python 3.6 reads and manipulates file contents. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template