Python 3 6 讀取並操作檔案內容的例項

2022-10-04 19:51:10 字數 1542 閱讀 2076

所使用python環境為最新的3.6版本

python中幾種對檔案的操作方法:

將a檔案複製到b檔案中去(保持原來格式)

讀取檔案中的內容,返回list列表 (載入本地詞典庫)

讀取檔案,返回檔案內容

#!/usr/bin/env python

# encoding: utf-8

"""@author: wugang

@contact: [email protected]

@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,www.cppcns.com encoding):

re =

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='ut程式設計客棧f-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 讀取並操作檔案內容的例項

本文位址:

linux 安裝python3 6 並設定預設

sudo apt get install software properties common安裝python3.6 sudo add apt repository ppa jonathonf python 3.6sudo apt get update sudo apt get install py...

利用檔案流來操作檔案(讀取)

1,readallbytes 函式,將檔案中的文字內容轉成byte陣列並返回。案例 讀取檔案,並輸出到控制台上 byte buffer file.readallbytes c users dell desktop new.txt 將位元組陣列中的每乙個元素都要按照我們指定的編碼格式解碼成字串 2,r...

配置python3 6的環境 檔案打包

為 注意 不可以修改檔案anaconda3的名字,否則會出現錯誤 2.方法 先安裝某乙個整合環境,例如anaconda3.5 在此環境下可以直接在終端輸入命令,安裝python2或者python3的環境,不需要像之前那樣雙擊 安裝 它自帶的是python3.6環境,如果你需要再安裝乙個python2...